如何使用JavaScript滚动到页面顶部?滚动条立即跳到页面顶部也是可取的,因为我不希望实现平滑滚动。
当前回答
旧的#top可以做到这一点
document.location.href = "#top";
适用于FF、IE和Chrome
其他回答
document.getElementsByTagName('html')[0].scrollIntoView({ behavior: "smooth" });
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;
});
}
如果您确实想要平滑滚动,请尝试以下操作:
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
这将接受href=“#top”的任何<a>标记,并使其平滑滚动到顶部。
平滑动画的更好解决方案:
// this changes the scrolling behavior to "smooth"
window.scrollTo({ top: 0, behavior: 'smooth' });
参考:https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo#Example
旧的#top可以做到这一点
document.location.href = "#top";
适用于FF、IE和Chrome