本文實(shí)例講述了JavaScript控制網(wǎng)頁平滑滾動(dòng)到指定元素位置的方法。分享給大家供大家參考。具體如下:
function elementPosition(obj) { var curleft = 0, curtop = 0; if (obj.offsetParent) { curleft = obj.offsetLeft; curtop = obj.offsetTop; while (obj = obj.offsetParent) { curleft += obj.offsetLeft; curtop += obj.offsetTop; } } return { x: curleft, y: curtop };}function ScrollToControl(id){ var elem = document.getElementById(id); var scrollPos = elementPosition(elem).y; scrollPos = scrollPos - document.documentElement.scrollTop; var remainder = scrollPos % 50; var repeatTimes = (scrollPos - remainder) / 50; ScrollSmoothly(scrollPos,repeatTimes); window.scrollBy(0,remainder);}var repeatCount = 0;var cTimeout;var timeoutIntervals = new Array();var timeoutIntervalSpeed;function ScrollSmoothly(scrollPos,repeatTimes){ if(repeatCount < repeatTimes) { window.scrollBy(0,50); } else { repeatCount = 0; clearTimeout(cTimeout); return; }repeatCount++;cTimeout = setTimeout("ScrollSmoothly('"+scrollPos+"','"+repeatTimes+"')",10);}使用方法:
ScrollToControl('elementID');頁面將會(huì)平滑的滾動(dòng)到元素elementID所在的位置
希望本文所述對(duì)大家的javascript程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注