JavaScript控制滚动条滚动到指定位置
1.打开一个网址,F12,定位到我们想到滚动的位置
比如定位到翻页的位置,我们可以取到翻页div的class=page-inner
2.在Consle输入滚动效果的Js代码:
1 function elementPosition(obj) { 2 var curleft = 0, curtop = 0; 3 if (obj.offsetParent) { 4 curleft = obj.offsetLeft; 5 curtop = obj.offsetTop; 6 while (obj = obj.offsetParent) { 7 curleft += obj.offsetLeft; 8 curtop += obj.offsetTop; 9 } 10 } 11 return { x: curleft, y: curtop }; 12 } 13 14 var repeatCount = 0; 15 var cTimeout; 16 var timeoutIntervals = new Array(); 17 var timeoutIntervalSpeed; 18 function ScrollSmoothly(scrollPos, repeatTimes) { 19 if (repeatCount < repeatTimes) { 20 window.scrollBy(0, 50); 21 } 22 else { 23 repeatCount = 0; 24 clearTimeout(cTimeout); 25 return; 26 } 27 repeatCount++; 28 cTimeout = setTimeout("ScrollSmoothly('" + scrollPos + "','" + repeatTimes + "')", 10); 29 } 30 31 function ScrollToControl(classname) { 32 var elem = document.getElementsByClassName(classname)[0]; 33 var scrollPos = elementPosition(elem).y - 200; //部分页面存在固定的Head部分 34 scrollPos = scrollPos - document.documentElement.scrollTop; 35 var remainder = scrollPos % 50; 36 var repeatTimes = (scrollPos - remainder) / 50; 37 ScrollSmoothly(scrollPos, repeatTimes); 38 window.scrollBy(0, remainder); 39 } 40 41 ScrollToControl("page-inner");
3.执行,效果如下: