CSS现在具有属性scroll-behavior
(有浏览器支持but not so great). 您可以将其用作described here:
html {
scroll-behavior: smooth;
}
@media (prefers-reduced-motion: reduce) {
html {
scroll-behavior: auto;
}
}
如果这对你不起作用,你就只能用JS了。问题是,在加载新页面时,浏览器会自动跳转到片段的位置。但有一个解决方法
described in this StackOverflow answer:
// to top right away
if (window.location.hash) scroll(0,0);
// void some browsers issue
setTimeout(function() { scroll(0,0); }, 1);
$(function() {
// *only* if we have anchor on the url
if(window.location.hash) {
// smooth scroll to the anchor id
$(\'html, body\').animate({
scrollTop: $(window.location.hash).offset().top + \'px\'
}, 1000, \'swing\');
}
});