<!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" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Document</title> <style> *{ padding:0; margin:0; } #demo{ 300px; height:500px; border:1px solid red; margin:100px; position:relative; } #demo #content{ 270px; float:left; margin-right:2px; position:absolute; left:0; top:0; } #demo #gd{ 28px; height:500px; background-color: gray; float:right; position: relative; } #demo #gd #bar{ 28px; position:absolute; top:0; right:0; background-color: red; height:50px; } </style> </head> <body> <div id="demo"> <div id="content"> 超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手 超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手 超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手 超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手 超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手 超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手 超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手 超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手 超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手 超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手超级辩手 </div> <div id="gd"> <div id="bar"></div> </div> </div> </body> </html> <script> var demo=document.getElementById("demo"); var content=document.getElementById("content"); var gd=document.getElementById("gd"); var bar=document.getElementById("bar"); bar .style.height=demo.offsetHeight/content.offsetHeight*demo.offsetHeight+"px"; //滚动条高度=容器高度/内容高度*容器高度 tuodong(bar,content); function tuodong(obj , target) //obj是拖拽的对象(bar滚动条),target是因为bar的拖拽移动的对象(content) { obj.onmousedown=function (event) { var event=event||window.event; var t=event.clientY-obj.offsetTop; //t是滚动条bar的顶部距离可视区顶部的距离 document.onmousemove=function (event) { var event=event||window.event; obj.style.top=event.clientY-t+"px"; //滚动条距离滚动条盒子的距离等于鼠标距离可视区顶部的距离减去bar的顶部距离可视区顶部的距离 if(parseInt(obj.style.top)<0) if-else的判断是为了让bar在gd(滚动条盒子)内移动 { obj.style.top=0; } else if(parseInt(obj.style.top)>demo.offsetHeight-obj.offsetHeight) { obj.style.top=demo.offsetHeight-obj.offsetHeight+"px"; } else{ //在滚动条正常移动的范围内,内容向上移动的高度等于(内容的高度-大盒子的高度)/(大盒子的高度-滚动条的高度)*滚动条移动的距离(即滚动条距离滚动条盒子顶部的高度) //因为content向上移动,所以加负号. target.style.top=-(target.offsetHeight-demo.offsetHeight)/(demo.offsetHeight-obj.offsetHeight)*(obj.offsetTop)+"px"; } window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); } } document.onmouseup=function () { document.onmousemove=null; } } </script>