如何在加载页面时禁用锚点跳转

dra*_*035 8 jquery scroll hashtag

当我访问时my_site.com/page.php#something,滚动位置是携带此特定主题标签而不是页面顶部的元素之一.

执行window.scrollTo(0, 0);并不会改变这一事实.什么可以呢?

编辑:还尝试了如何在加载页面时禁用锚点"跳转"的接受答案.似乎不再起作用了.

Lar*_*zan 15

您需要做的是存储hashtag以供以后使用,然后将其删除,以便浏览器没有任何要滚动的内容.

重要的是你不要把这部分代码放在$()或$(window).load()函数中,因为它会延迟并且浏览器已经移动到标记.

// 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 () {});
    }
});
Run Code Online (Sandbox Code Playgroud)


Dim*_*13i 5

拥有此HTML代码:

<a href="#test">link</a>
<div id="test"></div>
Run Code Online (Sandbox Code Playgroud)

您可以避免滚动到div元素,而是使用以下代码滚动到窗口的顶部:

$("a").on("click", function(e) {
    e.preventDefault();
    window.scrollTo(0, 0);
});
Run Code Online (Sandbox Code Playgroud)

编辑:

你可以尝试添加这个:

var firstVisit = true;
$(window).scroll(function() {
    if (firstVisit) {
        window.scrollTo(0, 0);
        firstVisit = false;
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,但问题不是当我单击任何内容时,而是当我“访问”页面时。 (2认同)