大家好!我在控制台中收到永久更新,但出现错误。(代码中的示例)。是否可以在没有无休止的 requestAnimationFrame 调用的情况下实际使用它,或者是否有其他更简洁、更宽敞的优化解决方案,告诉我?谢谢!
const
body = document.body,
scrollWrap = document.getElementsByClassName("main")[0],
height = scrollWrap.getBoundingClientRect().height - 1,
speed = 0.1;
var offset = 0;
body.style.height = Math.floor(height) + "px";
function smoothScroll() {
offset += (window.pageYOffset - offset) * speed;
var scroll = "translateY(-" + offset + "px) translateZ(0)";
scrollWrap.style.transform = scroll;
callScroll = requestAnimationFrame(smoothScroll);
}
smoothScroll();
<body>
<div class="main" style="display: flex; flex-direction: column; width: 100vw; height: 200vh">
<span>Text</span>
<div style="width: 10vw; height: 20vh; background-color: #000000"></div>
<span>Text</span>
<span>Text</span>
<div style="width: 10vw; height: 20vh; background-color: #000000"></div>
<span>Text</span>
</div>
<body>

该错误是由于
callScroll未声明该变量。为了不让requestAnimationFrame无休止的调用,需要创建一个滚动事件处理函数,并在其中启动一个动画,同样需要按时完成。条件
Math.abs(window.pageYOffset - offset) < 0.5非常适合这个。但是 callScroll 对我们很有用,可以在下一次滚动事件时取消之前安排的帧。
没有使用过渡的 requestAnimationFrame 有一个更简洁的解决方案: