javascript - 使用大参数时平滑滚动功能出现故障
问题描述
我编写了一个函数,可以将屏幕平滑滚动到点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,这是最奇怪的部分。为什么呢?我看不出算法有什么问题。
解决方案
从 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;
}
推荐阅读
- audio - 任何非基于 Chromium 的网络浏览器都无法加载某些 H264-mp4 视频
- html - 如何通过单击包含用户名的标签在 Angular 中打开一个新组件?
- html - net::ERR_NAME_NOT_RESOLVED,尝试通过 Chrome 或 Firefox 上的 HTML 链接获取谷歌字体时不允许错误的 URI 或跨站点访问
- python - 如何在不同时间调用python中的函数?
- java - JavaFX:从 FileChooser 获取图像并将其保存在一个字节 []
- wordpress - 为什么我的所有代码块都添加了水平滚动条?
- laravel - laravel 中的密码确认规则失败
- javascript - 有没有办法在 jsfiddle 上创建 API 并通过 JS fiddle 代码调用相同的 API?
- java - ConcurrentHashMap 相同sagement 上的读写器线程时的性能
- sql - ORDER BY 多个变量