1. 程式人生 > >js 寫一個滾動條

js 寫一個滾動條

兼容 absolut script name padding 位置 當前 sele osi

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自己練習寫一個滾動條</title>
<style>
*{
margin:0;
padding: 0;
}
.scroll{
margin:200px;
width:500px;
height:5px;
background: #ccc;
position: relative;
}
.bar{
width:10px;
height:20px;
background: #369369;
position: absolute;
top:-7px;
left:0;
cursor: pointer;
}
.mask{
position: absolute;
left:0;
top:0;
background: #369369;
width:0px;
height:5px;
}
</style>
</head>
<body>
<div class="scroll" id="scroll">
<div class="bar" id="bar"></div>
<div class="mask" id="mask"></div>
</div>
<p></p>
<script>
window.onload = function(){
var scroll = document.getElementById(‘scroll‘);
var bar = document.getElementById(‘bar‘);
var mask = document.getElementById(‘mask‘);
var ptxt = document.getElementsByTagName(‘p‘)[0];
bar.onmousedown = function (event){
// Event 對象代表事件的狀態,比如事件在其中發生的元素、鍵盤按鍵的狀態、鼠標的位置、鼠標按鈕的狀態。
// 事件通常與函數結合使用,函數不會在事件發生前被執行!
var event = event || window.event;
//相對於瀏覽器的x軸距離,,, 相對於父元素的左內邊距的距離
// 獲取到點擊軸的距離屏幕的距離
var leftVal = event.clientX - this.offsetLeft;
console.log(leftVal);
var that = this;
//拖動
document.onmousemove = function(event){
var event = event || window.event;
// 獲取移動的x軸距離,可能是正值,負值,
var barleft = event.clientX-leftVal;
//console.log(barleft);
console.log(scroll.offsetWidth);
console.log(bar.offsetWidth)
if(barleft<0){
barleft = 0;
//offsetWidth:元素在水平方向上占據的大小,無單位
}else if(barleft > scroll.offsetWidth - bar.offsetWidth){
barleft = scroll.offsetWidth - bar.offsetWidth;

}
mask.style.width = barleft+‘px‘;
that.style.left = barleft+‘px‘;
ptxt.innerHTML = ‘已經走啦‘ + parseInt(barleft/(scroll.offsetWidth-bar.offsetWidth)*100)+‘%‘;
//獲取光標的當前位置,這個是兼容寫法,後面的是ie8及以下的,

window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
}
};
document.onmouseup = function(){
document.onmousemove = null; //彈起鼠標不做任何操作
}
}
</script>
</body>
</html>

技術分享圖片

js 寫一個滾動條