水平拖动滚动条

时间:2023-01-26 22:48:32

   水平拖动滚动条

这个过程分为三步走: 

  一、分析首先获取元素 记得onmousemove 一定要写在onmousedown当中,善于利用var that=this 在onmosedown中最为重要的是获取移动的距离 首先是event.client-leftVal 的值;

  二、 判断移动的距离是否超出范围,由于that.style.left获取的是字符串所以使用 paseInt转化为数字判断。最后把移动的距离给遮罩盒子的宽度;
   三、鼠标移走的时候onmousemove d的值是null;

<!DOCTYPE html>

<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        * {margin:0;padding:0;}
        .scroll {
            width: 400px;
            height: 8px;
            background-color: #ccc;
            margin: 100px;
            position: relative;


        }
        .bar {
            width: 10px;
            height: 22px;
            background-color: #369;
            position: absolute;
            top: -7px;
            left: 0;
            cursor: pointer;
        }
        .mask {
            width: 0;
            height: 100%;
            background-color: #369;
            position: absolute;
             top: 0;
             left: 0;
        }
    </style>
</head>
<body>
<div class="scroll" id="scrollBar">
    <div class="bar"></div>
    <div class="mask"></div>
</div>
<div id="demo"></div>
</body>
</html>
<script>
var scrollBar=document.getElementById("srollBar");
var bar=scrollBar[0];
var mask=scrollBar[1];
var domo=scrollBar.nextSibling;
bar.onmousedown=function(){
var yuanX=this.client-scroll.offsetLeft;
var yuanY=this.clientY-scrpll.offsetTop;
}
bar.onmousemove=function(event){
var event=event || window.event;

var nowX=event.clientX-yuanX;
var nowY=event.clientY-yuanY;
mask.style.className="mask";

}
</script>
<script>
    var scrollBar = document.getElementById("scrollBar");
    var bar  = scrollBar.children[0];
    var mask = scrollBar.children[1];
    var demo = document.getElementById("demo");
   /* document.onmousedown = function() {
        alert(11);
    }*/

    bar.onmousedown = function(event) {
        var event = event || window.event;
        var leftVal = event.clientX - this.offsetLeft;
       // alert(11);
        // 拖动一定写到 down 里面才可以
        var that = this;
        document.onmousemove = function(event) {
            var event = event || window.event;
            that.style.left = event.clientX - leftVal  + 'px';
            //alert(that.style.left);
            var val = parseInt(that.style.left);
            if(val < 0)
            {
                that.style.left = 0;
            } else if(val > 390)
            {
                that.style.left = "390px";
            }
            mask.style.width = that.style.left;  // 遮罩盒子的宽度
            //计算百分比
            demo.innerHTML = "已经走了:"+ parseInt(parseInt(that.style.left) / 390 * 100) + "%";
            window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
        }
        document.onmouseup = function() {
            document.onmousemove = null;   // 弹起鼠标不做任何操作
        }
    }


</script>