How to disable anchor jump when loading a page

前端 未结 2 445
执笔经年
执笔经年 2020-12-16 03:49

When I visit my_site.com/page.php#something, the scroll position is the one of the element carrying this particular hashtag rather than the top of the page.

相关标签:
2条回答
  • 2020-12-16 04:02

    Having this HTML code:

    <a href="#test">link</a>
    <div id="test"></div>
    

    You can avoid scrolling to the div element and instead scrolling to the top of the window by using this code:

    $("a").on("click", function(e) {
        e.preventDefault();
        window.scrollTo(0, 0);
    });
    

    EDIT:

    You can try to add this:

    var firstVisit = true;
    $(window).scroll(function() {
        if (firstVisit) {
            window.scrollTo(0, 0);
            firstVisit = false;
        }
    });
    
    0 讨论(0)
  • 2020-12-16 04:16

    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.

    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 () {});
        }
    });
    
    0 讨论(0)
提交回复
热议问题