如何使用JavaScript滚动到页面顶部?滚动条立即跳到页面顶部也是可取的,因为我不希望实现平滑滚动。
当前回答
请检查以下代码,这肯定会有帮助。:)
document.querySelector('.sample-modal .popup-cta').scrollIntoView(true);
document.querySelector('.sample-modal').style.scrollPadding = '50px'; //to move to the top when scrolled up.
其他回答
<script>
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
</script>
html格式
<a href="#top">go top</a>
document.getElementById(“elem”)scrollIntoView();
您可以简单地使用链接中的目标,例如#someid,其中#someid是div的id。
或者,您可以使用任何数量的滚动插件,使其更加优雅。
http://plugins.jquery.com/project/ScrollTo是一个例子。
如果您想平滑滚动,请尝试以下操作:
$("a").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
另一种解决方案是JavaScript window.scrollTo方法:
window.scrollTo(x-value, y-value);
参数:
x值是沿水平轴的像素。y值是沿垂直轴的像素。
$(“.solltop”).click(函数){$(“html,body”).animate({scrollTop:0},“slow”);return false;});.节{高度:400px;}.第1节{背景色:#333;}.第2节{背景色:红色;}.第3节{背景色:黄色;}.第4节{背景色:绿色;}.滚动条{位置:固定;右:10px;底部:10px;颜色:#fff;}<html><head><title>滚动顶部演示</title><script src=“https://code.jquery.com/jquery-3.3.1.js“></script></head><body><div class=“content wrapper”><div class=“section section1”></div><div class=“section section2”></div><div class=“section section3”></div><div class=“section section4”></div>滚动顶部</a></div></body></html>