当用户单击我页面上的按钮时,它会在其下方创建一个新元素,然后向下滚动。我希望这可以顺利完成,并且可以像这样完成:window.scroll({ top: document.body.scrollHeight, behavior: "smooth" });
但是,这在 Safari 上不起作用,因此看来我需要使用自定义函数来获得此功能。
我四处搜寻,发现了这个(当前答案,但不是最理想的):
doScrolling = (elementY, duration) => {
let startingY = window.pageYOffset;
let diff = elementY - startingY;
var start;
// Bootstrap our animation - it will get called right before next frame shall be rendered.
window.requestAnimationFrame(function step(timestamp) {
if (!start) { start = timestamp; }
// Elapsed milliseconds since start of scrolling.
let time = timestamp - start;
// Get percent of completion in range [0, 1].
let percent = Math.min(time / duration, 1);
window.scrollTo(0, startingY + diff * percent);
let isScrollAtBottom = (window.innerHeight + window.pageYOffset) >= document.body.scrollHeight - 3;
if (isScrollAtBottom) { return; }
// Proceed with animation as long as we wanted it to.
if (time < duration) {
window.requestAnimationFrame(step);
}
})
}
像这样调用:this.doScrolling(document.body.scrollHeight, 750);
这似乎可行,但它似乎与 window.scroll
的语义不同.一方面,您需要指定持续时间,而使用
window.scroll
这是暗示的。其次,好像
window.scroll
使用不同的过渡类型?很难说,但感觉更像 ease
而不是 linear
过渡,开始缓慢,然后快速,然后减速停止。是否可以修改上述函数以模仿
window.scroll
的确切语义?这样您就无法分辨调用两者之间的区别?澄清一下,我不需要克隆
window.scroll
的所有功能。 .我唯一需要的是能够以流畅的方式滚动到给定位置(在我的情况下它始终是页面的末尾)。我在上面的问题中提供的功能几乎是完美的,只是它有点笨拙并且感觉不像 window.scroll
那样流畅.我想可能是动画风格?很难说为什么它看起来“更糟”,因为它是如此之快。
最佳答案
您可以尝试使用 AnimeJS
添加<script src="path/to/anime.min.js"></script>
到您的 HTML 页面
或通过 CDN 访问 https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.0/anime.min.js
接着
doScrolling = (elementY) => {
const startingY = window.pageYOffset
const diff = elementY - startingY
const obj = {
pos: startingY
}
const anime({
targets: obj,
pos: startingY + diff,
round: 1,
easing: 'easeInOutQuad',
update: function() {
window.scrollTo(0, obj.pos)
}
}).play()
}
关于javascript - 如何获得 Chrome 的精确平滑滚动功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64054992/