简体   繁体   中英

Smooth scroll work not correctly when using window.location.hash

I do smooth scroll. But it work not correctly. It only triggered when you press a second time, but hash change instantly in url.

$('nav').click(function(e){
        if(window.location.hash == "#block1") {
            $('html,body').animate({
                scrollTop: ($('#block1').offset().top)
            })
        }
        else if(window.location.hash == "#block2") {
            $('html,body').animate({
                scrollTop: ($('#block2').offset().top)
        })
        }
    })

You should prevent the default behaviour of the click event :

$('nav').click(function(e){
    e.preventDefault();
    //continue...

Hope this helps.

Edit :

This should do the trick :

$('nav').click(function(e){
    e.preventDefault();

    var section = $(this).attr('href');

    if(section == "#block1") {
        window.location.hash = "#block1";

        $('html,body').animate({
            scrollTop: ($('#block1').offset().top)
        });
    }
    else if(section == "#block2") {
        window.location.hash = "#block2";

        $('html,body').animate({
            scrollTop: ($('#block2').offset().top)
        });
    }
});

Valery

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM