简体   繁体   English

无法从固定菜单项顺利滚动才能正常工作

[英]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. 当用户单击“联系我们”链接以滚动到页脚中的联系信息时, 我在网站上使用以下Javascript创建平滑的滚动效果。 I got this code snippet from a comment by Devin Sturgeon on the CSS-Tricks post on smooth scrolling . 我从Devin Sturgeon在CSS-Tricks上有关平滑滚动的帖子中的评论中获得了此代码段。 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. 这行$('a[href*=#]:not([href=#])')返回一个空集,因此您的点击处理程序未设置在任何dom元素上。 The scrolling is being done by the browser using the old fashion anchor tag <a name="contact">&nbsp;</a> . 浏览器正在使用旧的时尚锚标签<a name="contact">&nbsp;</a>进行滚动。

@FakeRainBrigand is right, your document isn't fully loaded when you add your click handler. @FakeRainBrigand是正确的,添加单击处理程序时,文档未完全加载。 Just add it to the ready event. 只需将其添加到ready事件。

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

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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