重新加载页面时,我试图将页面对齐到顶部。为此,我像这样使用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与html元素一起使用,并将smooth作为behaviour传递,如下所示:

element.scrollIntoView({ block: 'start',  behavior: 'smooth' });

您可以在How to get the button when clicked go to a certain part of the page?中看到一个工作示例

07-24 09:50
查看更多