水平添加滚动条

 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title></title>
 6     <style>
 7         * {margin:0;padding:0;}
 8         .scroll {
 9             width: 400px;
10             height: 8px;
11             background-color: #ccc;
12             margin: 100px;
13             position: relative;
14 
15         }
16         .bar {
17             width: 10px;
18             height: 22px;
19             background-color: #369;
20             position: absolute;
21             top: -7px;
22             left: 0;
23             cursor: pointer;
24         }
25         .mask {
26             width: 0;
27             height: 100%;
28             background-color: #369;
29             position: absolute;
30             top: 0;
31             left: 0;
32         }
33     </style>
34 </head>
35 <body>
36 <div class="scroll" id="scrollBar">
37     <div class="bar"></div>
38     <div class="mask"></div>
39 </div>
40 <div id="demo"></div>
41 </body>
42 </html>
43 <script>
44     var scrollBar = document.getElementById("scrollBar");
45     var bar  = scrollBar.children[0];
46     var mask = scrollBar.children[1];
47     var demo = document.getElementById("demo");
48    /* document.onmousedown = function() {
49         alert(11);
50     }*/
51     bar.onmousedown = function(event) {
52         var event = event || window.event;
53         var leftVal = event.clientX - this.offsetLeft;
54        // alert(11);
55         // 拖动一定写到 down 里面才可以
56         var that = this;
57         document.onmousemove = function(event) {
58             var event = event || window.event;
59             that.style.left = event.clientX - leftVal  + 'px';
60             //alert(that.style.left);
61             var val = parseInt(that.style.left);
62             if(val < 0)
63             {
64                 that.style.left = 0;
65             } else if(val > 390)
66             {
67                 that.style.left = "390px";
68             }
69             mask.style.width = that.style.left;  // 遮罩盒子的宽度
70             //计算百分比
71             demo.innerHTML = "已经走了:"+ parseInt(parseInt(that.style.left) / 390 * 100) + "%";
72             window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
73         }
74         document.onmouseup = function() {
75             document.onmousemove = null;   // 弹起鼠标不做任何操作
76         }
77     }
78 
79 </script>

 

posted @ 2017-12-29 12:36  前端极客  阅读(389)  评论(0编辑  收藏  举报