水平拖动滚动条案例

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>Document</title>
    <style>
        #demo{
            width:400px;
            height:20px;
            background-color: gray;
            margin:100px;
            position: relative;
        }
        #demo #bar{
            width:10px;
            height:40px;
            background-color:pink;
            position:absolute;
            top:-10px;
            left:0;
        }
       #demo #jindu{
            width:0
            height:40px;
            background-color:pink;
            position:absolute;
            top:-10px;
            left:0;
        }
    </style>
</head>
<body>
    <div id="demo">
        <div id="bar"></div>
        <div id="jindu"></div>
    </div>
    <div id="wenzi"></div>
</body>
</html>
<script>
    var demo=document.getElementById("demo");
    var bar=document.getElementById("bar");
    var jindu=document.getElementById("jindu");
    var wenzi=document.getElementById("wenzi");
    bar.onmousedown=function (event)  //onmousedown当鼠标按下的时候
    {
        var event=event||window.event;
        var leftval=event.clientX-demo.offsetLeft;  //按下鼠标的时候,记录bar相对demo移动的距离
        //alert(leftval);
        document.onmousemove=function (event)   //拖动原理,鼠标按下接着移动鼠标,拖动一定写道按下里面
        {
            var event=event||window.event;
            bar.style.left=event.clientX-demo.offsetLeft-leftval +"px";//bar移动的距离
            if(parseInt(bar.style.left)<0)
            {
                bar.style.left=0;
            }
            if(parseInt(bar.style.left)>390)
            {
                bar.style.left=390+"px";
            }
            jindu.style.left=bar.style.left;
            wenzi.innerHTML="已经拖动"+parseInt((parseInt(bar.style.left)/390 *100))+"%";
            window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();//防止选择拖动
        }



        document.onmouseup=function () {
            document.onmousemove = null; //弹起鼠标不做任何操作
        }

    }
</script>

  

posted @ 2019-07-25 16:31  shanlu  阅读(219)  评论(0编辑  收藏  举报