Home >Web Front-end >JS Tutorial >JavaScript method to control smooth scrolling of web pages to the position of specified elements_javascript skills

JavaScript method to control smooth scrolling of web pages to the position of specified elements_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:03:192619browse

The example in this article describes how JavaScript controls the smooth scrolling of a web page to the position of a specified element. Share it with everyone for your reference. The details are as follows:

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

How to use:

ScrollToControl('elementID');

The page will scroll smoothly to the location of the element elementID

I hope this article will be helpful to everyone’s JavaScript programming design.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn