1、核心思想与之前的拖拽盒子是一样的
2、完全将鼠标在盒子中的坐标给滚动条是错的,因为这样会使滚动条顶部立刻瞬间移动到鼠标位置
3、必须在鼠标按下事件时记住鼠标在滚动条内部的坐标,再将鼠标在盒子中的坐标给滚动条时要减去这个相对距离
4、超出部分内容:超出部分移动距离=滚动条需要移动的距离:滚动条移动距离
5、上面公式的意思就是:滚动条移动到了能够移动距离的50%时,超出部分距离也应该移动50%
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> * { padding: 0; margin: 0; } .box { width: 250px; height: 400px; border: 1px solid #ccc; border-right: none; margin: 150px auto; padding: 10px; position: relative; overflow: hidden; } .content { width: 250px; font: 400 15px "simsun"; } .small { width: 20px; height: 100%; background-color: #ccc; position: absolute; top: 0; right: 0; } .scrollBar { width: 20px; height: 70px; background-color: red; border-radius: 15px; position: absolute; top: 0; left: 0; } </style> </head> <body> <div class="box"> <div class="content"> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> 少小离家老大回,乡音未改鬓毛衰<br> -----------最后-----------<br> </div> <div class="small"> <div class="scrollBar"></div> </div> <script> //点击滚动条,拖拽移动 var box = document.getElementsByTagName("div")[0]; var content = box.children[0]; var small = box.children[1]; var scrollBar = small.children[0]; scrollBar.onmousedown = function (ev) { ev = ev || window.event; var pageY = ev.pageY || scroll().top + ev.clientY; var scrollBarY = pageY - scrollBar.offsetTop - box.offsetTop;//鼠标在scrollBar中的位置 document.onmousemove = function (ev) { ev = ev || window.event; //鼠标在small中的坐标,其实就是在box中的坐标(只取y值) var pageY = ev.pageY || scroll().top + ev.clientY; var boxY = pageY - box.offsetTop; var y = boxY - scrollBarY; if (y < 0) { y = 0; } if (y > small.offsetHeight - scrollBar.offsetHeight) { y = small.offsetHeight - scrollBar.offsetHeight; } scrollBar.style.top = y + "px"; window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); //保证内容联动,滚动条拉到最下面,要保证内容部分显示底部 //滚动条最大移动距离: var scrollBarDistance = small.offsetHeight - scrollBar.offsetHeight;//滚动条可以滚动多长 var overContent = box.offsetHeight - 2 - 10 - content.offsetHeight;//超出部分 //scrollBarDistance/y=overContent/u; var u = overContent * y / scrollBarDistance; console.log(u); content.style.marginTop = u + "px"; } } document.onmouseup = function () { document.onmousemove = null; } function scroll() { return { "top": window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop, "left": window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft }; } </script> </div> </body> </html>