欢迎光临
我们一直在努力

JavaScript控制网页平滑滚动到指定元素位置的方法

本文实例讲述了JavaScript控制网页平滑滚动到指定元素位置的方法

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');

 

赞(0)
版权归原作者所有,如有侵权请告知。达维营-前端网 » JavaScript控制网页平滑滚动到指定元素位置的方法

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址