Home > Web Front-end > JS Tutorial > body text

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

WBOY
Release: 2016-05-16 16:03:19
Original
2595 people have browsed it

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);
}
Copy after login

How to use:

ScrollToControl('elementID');
Copy after login

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.

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template