如何使用JavaScript滚动到页面顶部?滚动条立即跳到页面顶部也是可取的,因为我不希望实现平滑滚动。
当前回答
滚动到的一个简单示例(使用html效率更高,但以下是如何使用JavaScript实现的):
const btn=document.querySelector('.btn');btn.addEventListener('click',()=>{window.scrollTo({左:0,顶部:0,})})window.addEventListener('scroll',函数(){const scrollHeight=window.pageYOffset;如果(滚动高度>500){btn.classList.add('sow-link');}其他{btn.classList.remove('sow-link');}});.节{衬垫底部:5rem;高度:90vh;}.磅{位置:固定;底部:3rem;右:3rem;背景:蓝色;宽度:2rem;高度:2rem;颜色:#fff;可见性:隐藏;z指数:-100;}.show链接{可见性:可见;z指数:100;}.标题h2{文本对齐:居中;}<section class=“section”><div class=“title”><h2>第一节</h2></div></section><section class=“section”><div class=“title”><h2>第二节</h2></div></section><section class=“section”><div class=“title”><h2>第三节</h2></div></section><a class=“btn”></a>
其他回答
使用window.scrowlTo(0,0);速度非常快所以我尝试了Mark Ursino的例子,但在Chrome中什么都没有发生我找到了这个
$('.showPeriodMsgPopup').click(function(){
//window.scrollTo(0, 0);
$('html').animate({scrollTop:0}, 'slow');//IE, FF
$('body').animate({scrollTop:0}, 'slow');//chrome, don't know if Safari works
$('.popupPeriod').fadeIn(1000, function(){
setTimeout(function(){$('.popupPeriod').fadeOut(2000);}, 3000);
});
});
测试了所有3种浏览器,并正常工作我正在使用蓝图css这是当客户点击“立即预订”按钮并且没有选择租赁期时,慢慢移动到日历所在的顶部,并打开一个指向2个字段的对话框div,3秒后它会消失
所有这些建议都适用于各种情况。对于通过搜索找到此页面的人,也可以尝试一下。JQuery,没有插件,滚动到元素。
$('html, body').animate({
scrollTop: $("#elementID").offset().top
}, 2000);
如果您想设置滚动动作的动画,则不需要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>
平滑滚动,纯javascript:
(function smoothscroll(){
var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
if (currentScroll > 0) {
window.requestAnimationFrame(smoothscroll);
window.scrollTo (0,currentScroll - (currentScroll/5));
}
})();
如果您确实想要平滑滚动,请尝试以下操作:
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
这将接受href=“#top”的任何<a>标记,并使其平滑滚动到顶部。