设定滚动位置


107

我试图在页面上设置滚动位置,以便将滚动条一直滚动到顶部。

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

(function () { alert('hello'); document.body.scrollTop = 0; } ());

有任何想法吗?

Answers:




34

请注意,如果要滚动元素而不是整个窗口,则元素没有scrollToand 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;

您还可以在本身不支持它的浏览器上,window.scrollTowindow.scrollBy功能模拟到网页中所有现有的HTML元素:

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
});

因此,您可以执行以下操作:

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

注意:Object.defineProperty鼓励您这样做,因为直接向中添加属性prototype是一种坏习惯(当您看到时:-)。


这很有帮助,谢谢。但是我发现元素确实具有'scrollTo'方法。请参阅developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollTo
Narvalex

@Narvalex是第二段所说的。
豪尔赫·富恩特斯·冈萨雷斯

我指出的参考资料表明这些功能是内置的。无需定义内置方法的属性
Narvalex,

@Narvalex哦,我刚刚读过“没有”,我不好。我必须指出,尽管当今很难找到这样的浏览器(例如IE11),但并不是所有的浏览器都具有它。
豪尔赫·富恩特斯·冈萨雷斯

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.