很多时候,由于美观上的考虑,往往需要自定义各种各样的滚动条,因此,本人做了一个demo
运行效果截图如下:
以下是代码部分:
<html> <head> <script type="text/javascript" src="https://www.jb51.net/jquery-1.9.1.min.js"></script> <script> $(function(){ //内容高度 var content = $("#div2"); //框的高度 var box = $("#div1"); //自定义的滚动条 var scrollbar = $("#div3"); var scroll=function(content,box,scrollbar){ var bigHeight = content.height(); var smallHeight = box.height(); var rate = smallHeight/bigHeight; var h = Math.floor(rate*smallHeight); scrollbar.height(h); var offset = box.offset() var offsetT = offset.top+1; scrollbar.mousedown(function(e){ var divOffsetT = scrollbar.offset().top; var tempT = e.pageY-divOffsetT; function move(e){ var newH = e.pageY-tempT-offsetT; if(newH<0){ newH=0; }else if(newH>(smallHeight-h)){ newH=smallHeight-h; } var rate2 = (newH+h)/smallHeight; var contentH = Math.floor(bigHeight*rate2-smallHeight); content.css("top",-contentH+"px"); scrollbar.css("top",newH+"px"); } $("body").on("mousemove",move); $("body").mouseup(function(){ $("body").off("mousemove",move); }); }); } scroll(content,box,scrollbar); }); </script> <style> *{ margin:0; padding: 0;} body{ font-size: 12px;} #div1{ width: 200px; height: 300px; margin: 50px auto; position: relative; _overflow: hidden; border: 1px solid #000;} #div2{ width: 180px; position: absolute; top: 0; left: 5px;} #div3{ width: 10px; position: absolute; top: 0; right:5px; background: #000;} </style> </head> <body> <div> <div></div> <div> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> 1<br> </div> </div> <textarea cols="30" rows="10"></textarea> </body> </html>