Change hash without reload in jQuery

前端 未结 5 1770
耶瑟儿~
耶瑟儿~ 2020-12-04 17:23

I have the following code:

$(\'ul.questions li a\').click(function(event) {
    $(\'.tab\').hide();
    $($(this).attr(\'href\')).fadeIn(\'slow\');
    event         


        
5条回答
  •  温柔的废话
    2020-12-04 18:08

    The accepted answer didn't work for me as my page jumped slightly on click, messing up my scroll animation.

    I decided to update the entire URL using window.history.replaceState rather than using the window.location.hash method. Thus circumventing the hashChange event fired by the browser.

    // Only fire when URL has anchor
    $('a[href*="#"]:not([href="#"])').on('click', function(event) {
    
        // Prevent default anchor handling (which causes the page-jumping)
        event.preventDefault();
    
        if ( location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname ) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
    
            if ( target.length ) {    
                // Smooth scrolling to anchor
                $('html, body').animate({
                    scrollTop: target.offset().top
                }, 1000);
    
                // Update URL
                window.history.replaceState("", document.title, window.location.href.replace(location.hash, "") + this.hash);
            }
        }
    });
    

提交回复
热议问题