重新加载页面时,我试图将页面对齐到顶部。为此,我像这样使用JavaScript:
window.onbeforeunload = function() {
window.scrollTo(0,0);
}
这对我非常有用,直到我在CSS中启用平滑滚动:
scroll-behavior: smooth;
现在它根本不起作用。
我想做的是暂时关闭JS这样的CSS平滑滚动行为:
window.onbeforeunload = function() {
document.getElementsByTagName("HTML")[0].style.scrollBehavior = "auto";
window.scrollTo(0,0);
}
但是看起来style.scrollBehavior无效,我找不到任何内容。是否可以通过JavaScript进行更改?
如果没有,那么在JavaScript中打开和关闭平滑滚动是非常简单的吗?
[我只是想尽可能保持直截了当。
您可以将scrollIntoView与通过smooth
作为behaviour
的html元素一起使用,如:
element.scrollIntoView({ block: 'start', behavior: 'smooth' });
您可以在How to get the button when clicked go to a certain part of the page?中看到一个有效的示例