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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:18:31  来源:igfitidea点击:

Set scroll position

javascript

提问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 annakata

Also worth noting window.scrollBy(dx,dy)(ref)

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

回答by Jorge Fuentes González

Note that if you want to scroll an element instead of the full window, elements don't have the scrollToand scrollBymethods. You should:

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

You can also mimic the window.scrollToand window.scrollByfunctions to all the existant HTML elements in the webpage on browsers that don't support it natively:

您还可以在本机不支持它的浏览器上模仿网页中所有现有 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
});

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.definePropertyis encouraged, as directly adding properties to the prototypeis a breaking bad habit (When you see it :-).

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

回答by maxime schoeni

... Or just replace bodyby documentElement:

...或者只是替换bodydocumentElement

document.documentElement.scrollTop = 0;