设置滚动位置

Mik*_*gin 94 javascript

我正在尝试在页面上设置滚动位置,以便滚动条一直滚动到顶部.

我想我需要这样的东西,但它不起作用:

(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)

  • 这让我很开心,woohoooooo (7认同)

ann*_*ata 47

还值得注意window.scrollBy(dx,dy)(参考)


Jor*_*lez 28

请注意,如果要滚动元素而不是整个窗口,则元素不具有scrollToscrollBy方法.你应该:

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.scrollTowindow.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是一个坏习惯(当你看到它:-).


max*_*eni 5

...或者只是替换bodydocumentElement

document.documentElement.scrollTop = 0;
Run Code Online (Sandbox Code Playgroud)