如何使用JavaScript滚动到页面顶部?滚动条立即跳到页面顶部也是可取的,因为我不希望实现平滑滚动。
当前回答
如果您想设置滚动动作的动画,则不需要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>
其他回答
尝试此操作以在顶部滚动
<script>
$(document).ready(function(){
$(window).scrollTop(0);
});
</script>
这将起作用:
window.srollTo(0,0);
许多用户建议同时选择html和body标签以实现跨浏览器兼容性,如下所示:
$('html, body').animate({ scrollTop: 0 }, callback);
如果你指望回调只运行一次,这可能会让你绊倒。它实际上会运行两次,因为您选择了两个元素。
如果这对你来说是个问题,你可以这样做:
function scrollToTop(callback) {
if ($('html').scrollTop()) {
$('html').animate({ scrollTop: 0 }, callback);
return;
}
$('body').animate({ scrollTop: 0 }, callback);
}
这在Chrome$('html')中有效的原因。scrollTop()返回0,但在其他浏览器(如Firefox)中无效。
如果滚动条已经位于顶部,您不想等待动画完成,请尝试以下操作:
function scrollToTop(callback) {
if ($('html').scrollTop()) {
$('html').animate({ scrollTop: 0 }, callback);
return;
}
if ($('body').scrollTop()) {
$('body').animate({ scrollTop: 0 }, callback);
return;
}
callback();
}
function scrolltop() {
var offset = 220;
var duration = 500;
jQuery(window).scroll(function() {
if (jQuery(this).scrollTop() > offset) {
jQuery('#back-to-top').fadeIn(duration);
} else {
jQuery('#back-to-top').fadeOut(duration);
}
});
jQuery('#back-to-top').click(function(event) {
event.preventDefault();
jQuery('html, body').animate({scrollTop: 0}, duration);
return false;
});
}
只需尝试,不需要其他插件/框架
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,正文{滚动行为:平滑;}