如何使用JavaScript滚动到页面顶部?滚动条立即跳到页面顶部也是可取的,因为我不希望实现平滑滚动。


当前回答

document.getElementsByTagName('html')[0].scrollIntoView({ behavior: "smooth" });

其他回答

平滑滚动,纯javascript:

(function smoothscroll(){
    var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
    if (currentScroll > 0) {
         window.requestAnimationFrame(smoothscroll);
         window.scrollTo (0,currentScroll - (currentScroll/5));
    }
})();

您可以简单地使用链接中的目标,例如#someid,其中#someid是div的id。

或者,您可以使用任何数量的滚动插件,使其更加优雅。

http://plugins.jquery.com/project/ScrollTo是一个例子。

如果您想平滑滚动,请尝试以下操作:

$("a").click(function() {
     $("html, body").animate({ scrollTop: 0 }, "slow");
     return false;
});

另一种解决方案是JavaScript window.scrollTo方法:

 window.scrollTo(x-value, y-value);

参数:

x值是沿水平轴的像素。y值是沿垂直轴的像素。

document.getElementById(“elem”)scrollIntoView();

你不需要JQuery。只需调用脚本

window.location = '#'

单击“转到顶部”按钮

示例演示:

输出.jsbin.com/fakumo#

PS:当你使用像angularjs这样的现代库时,不要使用这种方法。这可能会破坏URL散列。