1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>自定义滚动条</title> <style type="text/css"> *{ margin: 0; padding: 0; } #box{ width: 300px; height: 530px; margin: 40px auto; position: relative; overflow: hidden;
} #content{ width:285px; position: absolute; left: 0; top: 0; font-size: 20px; } #slide-box{ width: 15px; height: 530px; position: absolute; top: 0; right: 0; background-color: gainsboro; } #slide{ width: 15px; background-color: gray; position: absolute; top:0; left:0; border-radius: 7.5px; } </style> </head> <body> <div id="box"> <div id="content"> 内容区域
</div> <div id="slide-box"> <div id="slide"></div> </div> </div> </body> </html> <script type="text/javascript"> var slideBox = document.querySelector("#slide-box"); slide.style.height = box.offsetHeight / content.offsetHeight * slideBox.offsetHeight + "px"; box.onmousewheel = function(){ if(event.wheelDelta > 0){ content.style.top = content.offsetTop + 20 + "px"; if (content.offsetTop >= 0) { content.style.top = "0px"; } slide.style.top = -(content.offsetTop / content.offsetHeight) * slideBox.offsetHeight + "px"; }else{ content.style.top = content.offsetTop - 20 + "px"; if(content.offsetTop <=box.offsetHeight - content.offsetHeight){ content.style.top = box.offsetHeight - content.offsetHeight + "px"; } slide.style.top = -(content.offsetTop / content.offsetHeight) * slideBox.offsetHeight + "px"; } } slide.onmousedown = function(){ var t = event.clientY - this.offsetTop; slideBox.onmousemove = function(){ slide.style.top = event.clientY - t + "px"; if(slide.offsetTop <= 0){ slide.style.top = "0px"; } if(slide.offsetTop > slideBox.clientHeight - slide.offsetHeight){ slide.style.top = slideBox.clientHeight - slide.offsetHeight + "px"; } content.style.top = - slide.offsetTop / slideBox.offsetHeight * content.offsetHeight + "px"; } } slide.onmouseup = function(){ slideBox.onmousemove = null; } </script>
|