js controls scroll bar scrolling

 method one

JavaScript can  scrollTop control the scrolling of elements by operating attributes. The following is a simple example code:

var element = document.getElementById('myElement'); // 获取需要滚动的元素
element.scrollTop = 100; // 滚动到距离顶部100像素的位置

In the above example, by first  document.getElementById obtaining the element that needs to be scrolled, and then setting  scrollTop the property to the position that needs to be scrolled, you can control the scroll bar scrolling.

If you need smooth scrolling, you can use  window.requestAnimationFrame methods to achieve animation effects. The sample code is as follows:

var element = document.getElementById('myElement'); // 获取需要滚动的元素
var targetPosition = 100; // 滚动到距离顶部100像素的位置
var duration = 500; // 滚动动画的持续时间(毫秒)
var startTime = null; // 动画开始时间

function scrollTo(timestamp) {
  if (!startTime) startTime = timestamp;
  var progress = timestamp - startTime;
  var position = Math.min(progress / duration * targetPosition, targetPosition);
  element.scrollTop = position;
  if (progress < duration) {
    window.requestAnimationFrame(scrollTo);
  }
}

window.requestAnimationFrame(scrollTo); // 开始滚动动画

 In the above example, first get the element that needs to be scrolled and the target position, and then set the duration of the animation. In  scrollTo the function, a smooth scrolling effect is achieved by calculating the current progress and position. When the scroll animation is not completed, call  window.requestAnimationFrame a method to continue scrolling until the animation is completed.

 Method Two

 Get scroll distance

window.addEventListener('scroll', () => {
    scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
  })
const ScrollTop = (number = 0, time) => {
  if (!time) {
    document.body.scrollTop = document.documentElement.scrollTop = number;
    return number;
  }
  const spacingTime = 20; // 设置循环的间隔时间  值越小消耗性能越高
  let spacingInex = time / spacingTime; // 计算循环的次数
  let nowTop = document.body.scrollTop + document.documentElement.scrollTop; // 获取当前滚动条位置
  let everTop = (number - nowTop) / spacingInex; // 计算每次滑动的距离
  let scrollTimer = setInterval(() => {
    if (spacingInex > 0) {
      spacingInex--;
      ScrollTop(nowTop += everTop);
    } else {
      clearInterval(scrollTimer); // 清除计时器
    }
  }, spacingTime);
}

Call example

ScrollTop(scrollTop, 500)

Guess you like

Origin blog.csdn.net/qq_54123885/article/details/129882462