0

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>
4

1 回答 1

1

此行$('a[href*=#]:not([href=#])')返回一个空集,因此您的点击处理程序未设置在任何 dom 元素上。滚动是由浏览器使用老式锚标记完成的<a name="contact">&nbsp;</a>

@FakeRainBrigand 是对的,当您添加点击处理程序时,您的文档没有完全加载。只需将其添加到就绪事件中。

$(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;
                }
            }
        });

});
于 2013-07-09T01:07:13.493 回答