1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>自定义滚动条</title> 6 <style> 7 #parent{ 8 width: 600px; 9 height: 20px; 10 background: #ccc; 11 position: relative; 12 margin: 10px auto; 13 } 14 #div1{ 15 width: 20px; 16 height: 20px; 17 background: red; 18 position: absolute; 19 } 20 #div2{ 21 width: 300px; 22 height: 300px; 23 background: green; 24 filter: alpha(opcity:0); 25 opacity: 0; 26 } 27 </style> 28 </head> 29 <body> 30 <div id="parent"> 31 <div id="div1"></div> 32 </div> 33 34 <div id="div2"></div> 35 <script> 36 var oDiv = document.getElementById('div1'); 37 var Div2 = document.getElementById('div2'); 38 var oParent = document.getElementById('parent'); 39 40 var disX = 0; //鼠标的横向距离 41 42 oDiv.onmousedown = function(ev){ 43 var oEvent = ev || event; 44 disX = oEvent.clientX - oDiv.offsetLeft; 45 46 document.onmousemove = function(ev){ 47 var oEvent = ev || event; 48 var l = oEvent.clientX - disX; 49 50 51 if(l<0){ 52 l = 0; 53 } 54 if(l > oParent.offsetWidth - oDiv.offsetWidth){ 55 l = oParent.offsetWidth - oDiv.offsetWidth; 56 } 57 58 //根据最新的鼠标坐标来确定div的坐标 59 oDiv.style.left = l + 'px'; 60 61 var scale = l/(oParent.offsetWidth - oDiv.offsetWidth); 62 63 // Div2.style.width = 400*scale + 'px'; 64 // Div2.style.height = 400*scale + 'px'; 65 Div2.style.filter = 'alpha(opcity:' + scale*100 + ')'; 66 Div2.style.opacity = scale; 67 } 68 69 document.onmouseup = function(ev){ 70 document.onmousemove = null; 71 document.onmouseup = null; 72 } 73 74 //解决火狐拖拽的bug,取消默认事件 75 return false; 76 } 77 </script> 78 </body> 79 </html>
效果: