本文實例講述了jQuery自訂滾動條實作方法。分享給大家參考,具體如下:
很多時候,由於美觀上的考慮,往往需要自訂各種各樣的滾動條,因此,本人做了一個demo
運作效果截圖如下:
以下是程式碼部分:
<html> <head> <script type="text/javascript" src="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 id="div1"> <div id="div3"></div> <div id="div2"> 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 name="" id="txt" cols="30" rows="10"></textarea> </body> </html>
希望本文所述對大家jQuery程式設計有所幫助。