Javascript / CSS window.scrollTo(0,0) 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14622963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:25:43  来源:igfitidea点击:

Javascript / CSS window.scrollTo(0,0) not working

javascriptcss

提问by user1873468

I am building a web app, and part of that web app needs to scroll to the top when an action is performed. This is handled using window.scrollTo(0,0)which works perfectly until I add some CSS styling below (which I require for this project).

我正在构建一个 Web 应用程序,并且该 Web 应用程序的一部分需要在执行操作时滚动到顶部。这是使用window.scrollTo(0,0)which 完美地处理的,直到我在下面添加一些 CSS 样式(我需要这个项目)。

Has anybody got any idea why the CSS below would stop window.scrollTo(0,0)working?

有没有人知道为什么下面的 CSS 会停止window.scrollTo(0,0)工作?

* {
    -webkit-transform: translate3d(0,0,0);
    -moz-transform: translate3d(0,0,0);
    -ms-transform: translate3d(0,0,0);
    -o-transform: translate3d(0,0,0);
    transform: translate3d(0,0,0);
}

P.S. I cannot use jQuery in my situation, just in case it's suggested that I do that.

PS 我不能在我的情况下使用 jQuery,以防万一有人建议我这样做。

回答by Josue Alexander Ibarra

I had the same problem, this fixed it:

我有同样的问题,这解决了它:

document.getElementById('ELEMENT_ID').scrollIntoView();

document.getElementById('ELEMENT_ID').scrollIntoView();

Where ELEMENT_IDis the id of the object you want to scroll into view, in your case it would typically be the header.

ELEMENT_ID您要滚动到视图中的对象的 id在哪里,在您的情况下,它通常是标题。

Note this only works fully on Firefox browsers as the other browsers have yet to implement the smooth scrolling option (see more: http://caniuse.com/#feat=scrollintoview).

请注意,这仅适用于 Firefox 浏览器,因为其他浏览器尚未实现平滑滚动选项(请参阅更多信息:http: //caniuse.com/#feat=scrollintoview)。

回答by basarat

Try the alternative :

尝试替代方法:

document.body.scrollTop = 0;

回答by Dima

I my case removing this block fixed the issue

我的案例删除此块解决了问题

html, body {
  overflow-x: hidden;
}

回答by user1873468

Turns out there was not a set height on the main element in the body, which meant scroll to wasnt working however the transition CSS was giving the element height automatically in webkit.... Fixed the CSS to give it a set height and it works again!

结果发现主体中的主要元素没有设置高度,这意味着滚动到不起作用,但是过渡 CSS 在 webkit 中自动给出元素高度.... 修复了 CSS 以给它一个设置高度并且它可以工作再次!

回答by reubano

Changing

改变

html, body {
  overflow-x: hidden;
}

to

body {
  overflow-x: hidden;
}

worked for me

为我工作