首页 > 解决方案 > 使用大参数时平滑滚动功能出现故障

问题描述

我编写了一个函数,可以将屏幕平滑滚动到点dest像素。问题在于,每当滚动目的地(dETS)大于<body>所选的总高度时,即使到达<body>滚动的“停止”之后,滚动也永远不会停止(尝试向上滚动)。

function scroll(dest) {
  var x, scrollDist;
  if(dest > document.body.offsetHeight) {
    dest = document.body.offsetHeight;
  }
  console.log(document.body.offsetHeight);
  console.log(dest);
  x = setInterval(function() {
    // Calculate the scroll distance
    scrollDist = dest - window.scrollY;
    // Log the scroll distance at each iteration
    console.log(scrollDist);

    // If the scroll distance is greater than 10, scroll down 10px, otherwise
    // scroll down by an amount equal to scrollDist then stop scrolling
    if(Math.abs(scrollDist) >= 10) {
      // If the scroll distance is positive scroll down, otherwise scroll up
      if(scrollDist > 0) {
        window.scrollBy(0,2);
      } else {
        window.scrollBy(0,-2);
      }
    } else {
      window.scrollBy(0,scrollDist);
      clearInterval(x);
    }
  },1);
}
scroll(10000);

在此网页或任何其他正文高度小于 10000 像素的网页上尝试。通过查看控制台,您可以注意到在到达正文末尾后,scrollDist 继续记录为 410,这是最奇怪的部分。为什么呢?我看不出算法有什么问题。

标签: javascriptscroll

解决方案


从 dest 变量中减去页面高度

正如您的代码所代表的那样,代码计算要滚动的位置,window.scrollY即窗口顶部所在的高度。这意味着如果您尝试使用大于页面高度的值,它会尝试从页面底部达到 0 滚动距离,但不会考虑窗口的高度。它无法滚动过去的值(在您的情况下为 410 像素)是窗口高度。

window.innerHeight如果滚动距离太长,您可以通过从主体的偏移高度中减去来修复您的代码。

有问题的块应该从这个改变:

if (dest > document.body.offsetHeight) {  
  dest = document.body.offsetHeight;  
}

对此:

if (dest > document.body.offsetHeight) {  
  dest = document.body.offsetHeight - window.innerHeight;  
}

推荐阅读