Javascript 设置滚动位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4192847/
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
Set scroll position
提问by Mike Rifgin
I'm trying to set the scroll position on a page so the scroller is scrolled all the way to the top.
我正在尝试在页面上设置滚动位置,以便滚动条一直滚动到顶部。
I think I need something like this but it's not working:
我想我需要这样的东西,但它不起作用:
(function () { alert('hello'); document.body.scrollTop = 0; } ());
Any ideas?
有任何想法吗?
回答by Nick Craver
You can use window.scrollTo()
, like this:
你可以使用window.scrollTo()
,像这样:
window.scrollTo(0, 0); // values are x,y-offset
回答by Jorge Fuentes González
Note that if you want to scroll an element instead of the full window, elements don't have the scrollTo
and scrollBy
methods. You should:
请注意,如果您想滚动一个元素而不是整个窗口,则元素没有scrollTo
和scrollBy
方法。你应该:
var el = document.getElementById("myel"); // Or whatever method to get the element
// To set the scroll
el.scrollTop = 0;
el.scrollLeft = 0;
// To increment the scroll
el.scrollTop += 100;
el.scrollLeft += 100;
You can also mimic the window.scrollTo
and window.scrollBy
functions to all the existant HTML elements in the webpage on browsers that don't support it natively:
您还可以在本机不支持它的浏览器上模仿网页中所有现有 HTML 元素的window.scrollTo
和window.scrollBy
函数:
Object.defineProperty(HTMLElement.prototype, "scrollTo", {
value: function(x, y) {
el.scrollTop = y;
el.scrollLeft = x;
},
enumerable: false
});
Object.defineProperty(HTMLElement.prototype, "scrollBy", {
value: function(x, y) {
el.scrollTop += y;
el.scrollLeft += x;
},
enumerable: false
});
so you can do:
所以你可以这样做:
var el = document.getElementById("myel"); // Or whatever method to get the element, again
// To set the scroll
el.scrollTo(0, 0);
// To increment the scroll
el.scrollBy(100, 100);
NOTE: Object.defineProperty
is encouraged, as directly adding properties to the prototype
is a breaking bad habit (When you see it :-).
注意:Object.defineProperty
鼓励,因为直接向 中添加属性prototype
是一个坏习惯(当你看到它时:-)。
回答by maxime schoeni
... Or just replace body
by documentElement
:
...或者只是替换body
为documentElement
:
document.documentElement.scrollTop = 0;