如何使用JavaScript滚动到页面顶部?滚动条立即跳到页面顶部也是可取的,因为我不希望实现平滑滚动。
当前回答
你不需要JQuery。只需调用脚本
window.location = '#'
单击“转到顶部”按钮
示例演示:
输出.jsbin.com/fakumo#
PS:当你使用像angularjs这样的现代库时,不要使用这种方法。这可能会破坏URL散列。
其他回答
如果您确实想要平滑滚动,请尝试以下操作:
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
这将接受href=“#top”的任何<a>标记,并使其平滑滚动到顶部。
这样做不需要jQuery。一个标准的HTML标记就足够了。。。
<div id="jump_to_me">
blah blah blah
</div>
<a target="#jump_to_me">Click Here To Destroy The World!</a>
如果您想设置滚动动作的动画,则不需要javascript、event!
CSS:
html {
scroll-behavior: smooth;
}
HTML格式:
<html>
<body>
<a id="top"></a>
<!-- your document -->
<a href="#top">Jump to top of page</a>
</body>
</html>
你可以尝试在这个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>
非jQuery解决方案/纯JavaScript:
document.body.scrollTop = document.documentElement.scrollTop = 0;