自制一个滚动条

参考文章:【https://blog.csdn.net/u014205965/article/details/45972803

 1 <html>
 2     <head>
 3         <title>自定义滚动条</title>
 4         <style>
 5             #parent{
 6                 width: 400px;
 7                 height: 30px;
 8                 background: lightgrey;
 9                 position: relative;
10             }
11 
12             #child{
13                 width: 30px;
14                 height: 30px;
15                 background: greenyellow;
16                 position: absolute;
17             }
18             #box {
19                 width: 0;
20                 height: 0;
21                 background: blueviolet;
22             }
23         </style>
24     </head>
25     <body>
26         <div id="parent">
27             <div id="child"></div>
28         </div>
29         <div id="box"></div>
30         <script>
31 
32             window.onload=function() {
33                 var oParent = document.getElementById('parent');
34                 var oChild = document.getElementById('child');
35                 var disX = 0;
36                 oChild.onmousedown = function (ev) {
37                     var ev = ev || window.event;
38                     disX = ev.clientX - oChild.offsetLeft;
39                     document.onmousemove = function (ev) {
40                         var ev = ev || window.event;
41                         var oBox = document.getElementById('box');
42                         // 限制小Div拖动范围
43                         var L = ev.clientX - disX;
44 
45                         if (L<0) {
46                             //因为小div是相对大div定位的,所以当拖到大div的最左边的时候,小div的left就为0了
47                             L = 0;
48                         }
49 
50                         if (L > oParent.offsetWidth - oChild.offsetWidth) {
51                             L = oParent.offsetWidth - oChild.offsetWidth;
52                         }
53 
54                         // 定义一个滚动的比例,因为L的大小是由上面的判断语句决定的,所以scale需要定义在判断语句下面,定义在上面会出问题
55                         var scale = L/(oParent.offsetWidth - oChild.offsetWidth);
56                         oChild.style.left = L + 'px';
57                         oBox.style.width = scale * 300 + 'px';
58                         oBox.style.height = scale * 300 + 'px';
59                         
60                     }
61                     document.onmouseup = function () {
62                         document.onmousemove = null;
63                         document.onmouseup = null;  
64                     }
65                     return false;
66                 }
67             }
68         </script>
69     </body>
70 </html>

猜你喜欢

转载自www.cnblogs.com/keepee/p/12227675.html