简体   繁体   中英

Can't get smooth scrolling from fixed menu item to work

I'm using the following Javascript on my web site to create a smooth scrolling effect when the user clicks the Contact Us link, to scroll to the contact information in the footer. I got this code snippet from a comment by Devin Sturgeon on the CSS-Tricks post on smooth scrolling . My only guess is that the issue arises from the fact that the anchor link is not in a set position, but in the fixed menu. According to the post, the snippet should work simply by cutting and pasting it in.

<script type="text/javascript">
    $('a[href*=#]:not([href=#])').click(function() {
        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) {
                $('html,body').animate({
                     scrollTop: target.offset().top
                }, 1000);
                return false;
            }
        }
    });
</script>

this line $('a[href*=#]:not([href=#])') is returning an empty set so your click handler is not being set on any dom element. The scrolling is being done by the browser using the old fashion anchor tag <a name="contact">&nbsp;</a> .

@FakeRainBrigand is right, your document isn't fully loaded when you add your click handler. Just add it to the ready event.

$(document).ready(function() {

        $('a[href*=#]:not([href=#])').click(function() {
            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) {
                     $('html,body').animate({
                         scrollTop: target.offset().top - 181
                    }, 1000);
                    return false;
                }
            }
        });

});

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