<div id="contentBox"> <div id="content"> <p>1</p> <p>2</p> <p>3</p> <p>4</p> <p>5</p> <p>6</p> <p>7</p> <p>8</p> <p>9</p> </div> </div> <div id="scrollBar"> <div id="scroll"></div> </div>
#contentBox{ width: 100px; height: 100px; border:1px solid darkgray; overflow: hidden; position: relative; } #content{ position: absolute; left: 0; top: 0; } #scrollBar { position: relative; width: 200px; height: 30px; background: grey; } #scroll{ position: absolute; width: 30px; height: 30px; background: red; } *{ margin: 0; padding: 0; }
var scroll=document.getElementById('scroll'); var scrollBar=document.getElementById('scrollBar'); var content=document.getElementById('content'); var contentBox=document.getElementById('contentBox'); var toppos=content.offsetHeight-contentBox.offsetHeight; scroll.onmousedown= function (e) { var e= e||window.event; var disX= e.clientX-scroll.offsetLeft; document.onmousemove= function (e) { var e= e || window.event; var left=e.clientX-disX; if(left<0){ left=0; }else if(left>(scrollBar.offsetWidth-scroll.offsetWidth)){ left=scrollBar.offsetWidth-scroll.offsetWidth; } var scale=left/(scrollBar.offsetWidth-scroll.offsetWidth); content.style.top=-scale*toppos+'px'; scroll.style.left= left+'px'; } document.onmouseup= function () { document.onmousemove=null; document.onmouseup=null; } } //top 是一个自带的全局变量,表示window