<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>滚动条</title <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script <style type="text/css">*{margin:0; padding:0;} .wrapper{ width:500px; height:500px; border:1px solid #000; margin:0 auto; } .content{ width:445px; height:400px; overflow:hidden; text-indent:2em;margin:50px 0 0 20px; float:left; line-height:22px;} .track{ width:15px; height:400px; background:#ccc; float:right; margin:50px 10px 0 0 ;} .track .thum{ width:15px; height:30px; background:#eee; cursor:pointer; position:absolute; }</style </head <body> <div class="wrapper"> <div class="content"> <div> 哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈 美美美美美美美美美美美美美美美美美美美美美美美美美美美美美美美美美美美美美美美23 </div </div <div class="track"> <div class="thum"></div </div </div <script type="text/javascript">if($(".content div").height()<400){ $(".track").hide(); }else{ $(".track").show(); } var thumheight=(400/$(".content div").height())*400; $(".thum").height(thumheight); $(".thum").mousedown(function(e){ $(document).bind('selectstart',function( ){ return false;}) var eboj=e||window.event; var y1=eboj.pageY-$(".thum").position().top; $(document).mousemove(function(e){ var eboj=e||window.event; var y2=eboj.pageY-y1; var t=$(".track").offset().top+400-$(".thum").height(); var t1=$(".track").offset().top; var mtop=($(".thum").offset().top-$(".track").offset().top)*$(".content div").height()/400; y2=y2>t?t:y2; y2=y2<t1?t1:y2; $(".thum").css("top",y2); $(".content div").css("margin-top",-mtop); }) $(document).mouseup(function(){ $(document).unbind('mouseup').unbind('mousemove').unbind('selectstart'); }) })</script </body </html 要点:1.点击的时候,禁止文本选中:$(document).bind('selectstart',function(){return false;});
2.拖动的时候,拖动事件加在document上;
3.div滚动的高度/div滚动部分内容的高度=滑块距滚槽顶部的高度/滚槽的高度;
4.解除绑定事件要写在mousedown事件里面;