我正在尝试在页面上设置滚动位置,以便滚动条一直滚动到顶部.
我想我需要这样的东西,但它不起作用:
(function () { alert('hello'); document.body.scrollTop = 0; } ());
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
Nic*_*ver 161
你可以window.scrollTo()
像这样使用:
window.scrollTo(0, 0); // values are x,y-offset
Run Code Online (Sandbox Code Playgroud)
Jor*_*lez 28
请注意,如果要滚动元素而不是整个窗口,则元素不具有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;
Run Code Online (Sandbox Code Playgroud)
您还可以模拟网页中所有现有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
});
Run Code Online (Sandbox Code Playgroud)
所以你可以这样做:
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);
Run Code Online (Sandbox Code Playgroud)
注意:Object.defineProperty
鼓励,因为直接添加属性prototype
是一个坏习惯(当你看到它:-).
...或者只是替换body
为documentElement
:
document.documentElement.scrollTop = 0;
Run Code Online (Sandbox Code Playgroud)