JavaScript實現(xiàn)垂直滾動條效果
本文實例為大家分享了js垂直滾動條的實現(xiàn)代碼,供大家參考,具體內(nèi)容如下
1、紅色盒子高度計算公式:
容器的高度 / 內(nèi)容的高度 * 容器的高度
2、紅色方塊移動一像素 ,我們的內(nèi)容盒子移動多少呢?
(內(nèi)容盒子高度 - 大盒子高度) / (大盒子高度 - 紅色盒子的高度) 計算倍數(shù)
(內(nèi)容盒子高度 - 大盒子高度)/ (大盒子高度 - 紅色盒子的高度) * 紅色盒子移動的數(shù)值
<html>
<head>
<meta charset="UTF-8">
<title>垂直滾動條</title>
<style>
*{
padding: 0;
margin: 0;
}
.box{
width: 300px;
height: 500px;
border: 1px solid red;
padding-right: 20px;
margin: 100px;
position: relative;
}
.content{
padding: 5px 18px 10px 5px;
position: absolute;
left: 0;
top: -10px;
}
.scroll{
position: absolute;
top: 0;
right: 0;
background-color: #ccc;
width: 20px;
height: 100%;
}
.bar{
width: 100%;
height: 20px;
background-color: red;
border-radius: 10px;
position: absolute;
left: 0;
top: 0;
cursor: pointer;
}
</style>
</head>
<body>
<div class="box" id="box">
<div class="content">
三觀不同,一句話都嫌多。我想,人和人之間一定存在磁場這回事,沿著三觀向外輻射。
…………
</div>
<div class="scroll">
<div class="bar"></div>
</div>
</div>
<script>
var box = document.getElementById('box');
var content = box.children[0];
var scroll = box.children[1];
var bar = scroll.children[0];
//計算滾動條紅色bar的長度:容器長度/內(nèi)容長度 * 容器長度,,比例關(guān)系
bar.style.height = box.offsetHeight / content.offsetHeight * box.offsetHeight +"px";
bar.onmousedown = function(event){
var event = event || window.event;
var y = event.clientY - this.offsetTop;
document.onmousemove = function(event){
var event = event || window.event;
var top = event.clientY - y;
if(top < 0)
top =0;
else if(top > scroll.offsetHeight - bar.offsetHeight)
top = scroll.offsetHeight - bar.offsetHeight;
bar.style.top = top +"px";
//(內(nèi)容盒子高度 - 大盒子高度) / (大盒子高度 - 紅色盒子的高度) * 紅色盒子移動的數(shù)值
content.style.top = -(content.offsetHeight - box.offsetHeight)/(box.offsetHeight - bar.offsetHeight)*top+"px";
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); // 防止拖動滑塊的時候, 選中文字
}
}
document.onmouseup = function(){
document.onmousemove = null;
}
</script>
</body>
</html>
效果:

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JS使用Date對象實時顯示當(dāng)前系統(tǒng)時間簡單示例
這篇文章主要介紹了JS使用Date對象實時顯示當(dāng)前系統(tǒng)時間,涉及javascript基于定時器動態(tài)操作Date對象相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2018-08-08
JavaScript建立一個語法高亮輸入框?qū)崿F(xiàn)思路
通常網(wǎng)站自帶的textarea編輯器不能滿足我們的需求比如高亮顯示代碼等,在這篇文章中,我將使用JavaScript庫ACE來創(chuàng)建一個輸入框效果,該腳本允許開發(fā)人員創(chuàng)建支持語法高亮的輸入框,感興趣的你可不要錯過了哈2013-02-02
javascript 利用Image對象實現(xiàn)的埋點(某處的點擊數(shù))統(tǒng)計
統(tǒng)計用戶頁面某處的點擊數(shù)或者執(zhí)行到程序中某個點的次數(shù);根據(jù)實際情況,創(chuàng)建多個Image對象,原則誰空閑誰做事,解下來詳細介紹,需要了解的朋友可以參考下2012-12-12
JavaScript中字符串GBK與GB2312的編解碼示例講解
在瀏覽器JavaScript環(huán)境中,可以使用TextEncoder和TextDecoder?API?來進行?GBK?編碼和解碼,也可以使用?encodeURIComponent?函數(shù)對字符串進行編碼,最好使用第三方庫,比如iconv-lite來實現(xiàn)2023-12-12
JavaScript搜索字符串并將搜索結(jié)果返回到字符串的方法
這篇文章主要介紹了JavaScript搜索字符串并將搜索結(jié)果返回到字符串的方法,涉及javascript中match方法操作字符串的技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-04-04

