如何使用JavaScript滚动到页面顶部?滚动条立即跳到页面顶部也是可取的,因为我不希望实现平滑滚动。
当前回答
<script>
$(function(){
var scroll_pos=(0);
$('html, body').animate({scrollTop:(scroll_pos)}, '2000');
});
</script>
编辑:
$('html, body').animate({scrollTop:(scroll_pos)}, 2000);
另一种上下边距滚动方式:
window.scrollTo({ top: 100, left: 100, behavior: 'smooth' });
其他回答
请检查以下代码,这肯定会有帮助。:)
document.querySelector('.sample-modal .popup-cta').scrollIntoView(true);
document.querySelector('.sample-modal').style.scrollPadding = '50px'; //to move to the top when scrolled up.
所有这些建议都适用于各种情况。对于通过搜索找到此页面的人,也可以尝试一下。JQuery,没有插件,滚动到元素。
$('html, body').animate({
scrollTop: $("#elementID").offset().top
}, 2000);
您可以简单地使用链接中的目标,例如#someid,其中#someid是div的id。
或者,您可以使用任何数量的滚动插件,使其更加优雅。
http://plugins.jquery.com/project/ScrollTo是一个例子。
滚动到带有动画的页面顶部:
window.scrollTo({ top: 0, behavior: 'smooth' });
滚动到的一个简单示例(使用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>