如何使用JavaScript滚动到页面顶部?滚动条立即跳到页面顶部也是可取的,因为我不希望实现平滑滚动。
当前回答
试试这个
<script>
$(function(){
$('a').click(function(){
var href =$(this).attr("href");
$('body, html').animate({
scrollTop: $(href).offset().top
}, 1000)
});
});
</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>
平滑滚动,纯javascript:
(function smoothscroll(){
var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
if (currentScroll > 0) {
window.requestAnimationFrame(smoothscroll);
window.scrollTo (0,currentScroll - (currentScroll/5));
}
})();
如果您想滚动到具有ID的任何元素,请尝试以下操作:
$('a[href^="#"]').bind('click.smoothscroll',function (e) {
e.preventDefault();
var target = this.hash;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 700, 'swing', function () {
window.location.hash = target;
});
});``
尝试此操作以在顶部滚动
<script>
$(document).ready(function(){
$(window).scrollTop(0);
});
</script>
非jQuery解决方案/纯JavaScript:
document.body.scrollTop = document.documentElement.scrollTop = 0;