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


当前回答

平滑滚动,纯javascript:

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

其他回答

您可以使用javascript的内置函数scrollTo:

函数滚动(){window.scrollTo({顶部:0,行为:“平滑”});}<button onclick=“scroll”>滚动</button>

尝试以下代码:

$('html, body').animate({
    scrollTop: $("div").offset().top
}, time);

div=>要移动滚动的Dom元素。

时间=>毫秒,定义滚动速度。

平滑动画的更好解决方案:

// this changes the scrolling behavior to "smooth"
window.scrollTo({ top: 0, behavior: 'smooth' });

参考:https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo#Example

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

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

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

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

参数:

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

你可以尝试在这个Fiddle中使用JShttp://jsfiddle.net/5bNmH/1/

在页脚中添加“转到顶部”按钮:

<footer>
    <hr />
    <p>Just some basic footer text.</p>
    <!-- Go to top Button -->
    <a href="#" class="go-top">Go Top</a>
</footer>