How can I remove the location hash without causing the page to scroll?

后端 未结 8 1572
情深已故
情深已故 2020-12-04 08:18

Is it possible to remove the hash from window.location without causing the page to jump-scroll to the top? I need to be able to modify the hash without causing

相关标签:
8条回答
  • 2020-12-04 08:58

    Have you tried return false; in the event handler? jQuery does something special when you do that, similar to, but AFAIK more impactful, than e.preventDefault.

    0 讨论(0)
  • 2020-12-04 09:00

    Setting window.location.hash to empty or non-existing anchor name, will always force the page to jump to top. The only way to prevent this is to grab the scroll position of the window and set it to that position again after the hash change.

    This will also force a repaint of the page (cant avoid it), though since it's executed in a single js process, it won't jump up/down (theoretically).

    $('<a href="#123">').text('link').click(function(e) {
        e.preventDefault();
        window.location.hash = this.hash;
    }).appendTo('body');
    
    $('<a href="#">').text('unlink').click(function(e) {
        e.preventDefault();
        var pos = $(window).scrollTop(); // get scroll position
        window.location.hash = '';
        $(window).scrollTop(pos); // set scroll position back
    }).appendTo('body');
    

    Hope this helps.

    0 讨论(0)
提交回复
热议问题