如何使用JavaScript滚动到页面顶部?滚动条立即跳到页面顶部也是可取的,因为我不希望实现平滑滚动。
当前回答
document.getElementsByTagName('html')[0].scrollIntoView({ behavior: "smooth" });
其他回答
真的很奇怪:这个问题已经活跃了五年了,但仍然没有一个普通的JavaScript答案来激活滚动……所以,现在就开始吧:
var scrollToTop = window.setInterval(function() {
var pos = window.pageYOffset;
if ( pos > 0 ) {
window.scrollTo( 0, pos - 20 ); // how far to scroll on each step
} else {
window.clearInterval( scrollToTop );
}
}, 16); // how fast to scroll (this equals roughly 60 fps)
如果愿意,可以将其包装在函数中,并通过onclick属性调用它。检查这个jsfiddle
注意:这是一个非常基本的解决方案,可能不是最有效的解决方案。这里可以找到一个非常详细的示例:https://github.com/cferdinandi/smooth-scroll
document.getElementsByTagName('html')[0].scrollIntoView({ behavior: "smooth" });
尝试此操作以在顶部滚动
<script>
$(document).ready(function(){
$(window).scrollTop(0);
});
</script>
滚动到的一个简单示例(使用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>
只需尝试,不需要其他插件/框架
document.getElementById(“jarscoolbtn”).addEventListener(“单击”,jarsrollfunction);函数jarrollfunction(){var body=document.body;//对于Safarivar html=document.documentElement;//Chrome、Firefox、IE和Operabody.scrollTop=0;html.scrollTop=0;}<button id=“jarscoolbtn”>滚动内容</button>html,正文{滚动行为:平滑;}