如何使用JavaScript滚动到页面顶部?滚动条立即跳到页面顶部也是可取的,因为我不希望实现平滑滚动。
当前回答
您可以使用javascript的内置函数scrollTo:
函数滚动(){window.scrollTo({顶部:0,行为:“平滑”});}<button onclick=“scroll”>滚动</button>
其他回答
试试这个
<script>
$(function(){
$('a').click(function(){
var href =$(this).attr("href");
$('body, html').animate({
scrollTop: $(href).offset().top
}, 1000)
});
});
</script>
纯JavaScript解决方案:
function scrollToTop() {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
我在Codepen上编写了一个动画解决方案
此外,您可以尝试使用CSS滚动行为的另一种解决方案:smooth属性。
html {
scroll-behavior: smooth;
}
@media (prefers-reduced-motion: reduce) {
html {
scroll-behavior: auto;
}
}
有趣的是,其中大多数根本不适合我,所以我使用了jQuery-ScrollTo.js:
wrapper.find(".jumpToTop").click(function() {
$('#wrapper').ScrollTo({
duration: 0,
offsetTop: -1*$('#container').offset().top
});
});
它奏效了$(document).sollTop()返回了0,而这个函数实际上起了作用。
动机
这个简单的解决方案在本地工作,并实现了到任何位置的平滑滚动。
它避免了使用锚链接(带有#的链接),在我看来,如果你想链接到一个部分,这些链接是有用的,但在某些情况下不是很舒服,特别是当指向顶部时,这可能会导致两个不同的URL指向同一位置(http://www.example.org和http://www.example.org/#).
解决方案
在要滚动到的标记中添加一个id,例如第一个部分,它回答了这个问题,但id可以放在页面的任何位置。
<body>
<section id="top">
<!-- your content -->
</section>
<div id="another"><!-- more content --></div>
然后,作为一个按钮,您可以使用链接,只需使用如下代码编辑onclick属性即可。
<a onclick="document.getElementById('top').scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' })">Click me</a>
其中document.getElementById的参数是单击后要滚动到的标记的id。
如果您确实想要平滑滚动,请尝试以下操作:
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
这将接受href=“#top”的任何<a>标记,并使其平滑滚动到顶部。