jQuery get hash of element using .on() event

后端 未结 2 1102
-上瘾入骨i
-上瘾入骨i 2020-12-17 17:25

Before I get flamed with references to manuals, I have been researching this for quite some time, and keep getting dead ends. Not even sure how to debug it properly. So if

相关标签:
2条回答
  • 2020-12-17 18:01

    Your a element doesn't have a hash attribute. try getting the href attribute and using javascript's substr and indexOf functions to split the string at the #

    var href = $(this).attr("href");
    var hash = href.substr(href.indexOf("#"));
    

    You can also use

    $(this).prop("hash");
    
    0 讨论(0)
  • 2020-12-17 18:12
    $('a.js-hash').click(function() {
    
        // Store hash
        var hash = this.hash;
    
        // Using jQuery's animate() method to add smooth page scroll
        $('html, body').animate({
            scrollTop: $(hash).offset().top
        }, 1000, function() {
    
            // Add hash (#) to URL when done scrolling (default click behavior)
            window.location.hash = hash;
        });
    
        // Prevent default anchor click behavior
        return false;
    });
    
    0 讨论(0)
提交回复
热议问题