更新时间:2022-01-08 04:58:24
您需要做的是存储主题标签以备后用,然后将其删除,这样浏览器就不会滚动到任何内容.
What you have to do is store the hashtag for later use and then delete it so that the browser doesn't have anything to scroll to.
重要的是不要把那部分代码放在 $() 或 $(window).load() 函数中,因为这会很晚并且浏览器已经移动到标签.
It is important that you do not put that part of the code in the $() or $(window).load() functions as it would be to late and the browser already have moved to the tag.
// store the hash (DON'T put this code inside the $() function, it has to be executed
// right away before the browser can start scrolling!
var target = window.location.hash,
target = target.replace('#', '');
// delete hash so the page won't scroll to it
window.location.hash = "";
// now whenever you are ready do whatever you want
// (in this case I use jQuery to scroll to the tag after the page has loaded)
$(window).load(function() {
if (target) {
$('html, body').animate({
scrollTop: $("#" + target).offset().top
}, 700, 'swing', function () {});
}
});