使用主导航滚动网站问题

时间:2014-08-28 20:44:57

标签: javascript jquery html

我为我的网站构建了一个滚动主页,允许用户点击标题中的链接向下滚动到网站的不同部分。我还有新页面的外部链接,允许用户查看不同的项目 无论出于何种原因,它都很有效,但是只要我到达其中一个项目页面,然后尝试单击主页,或者工作链接无法正常工作。没有创建第二个header.php
如何让nav全球工作。

<script>
$(document).ready(function(){
        $('a.logo, ul.nav a, #mmenu a, a.mobileLogo').bind('click',function(event){
            var $anchor = $(this);

            href_arr = $anchor.attr('href').split("#");

            $('html, body').stop().animate({
                scrollTop: $('#'+href_arr[1]).offset().top - 0
            }, 500);   // it was -70                 
            event.preventDefault();
        }); 
     });
});
</script>

我的链接看起来像这样......

    <a href="/#home">Link</a>
    <a href="/#work">Work</a>

关于如何修复jQuery以便它在外部页面上工作的任何想法?

1 个答案:

答案 0 :(得分:0)

听起来您的产品页上不存在#home#work,对吗?如果是这种情况,那么调用event.preventDefault()实际上会阻止浏览器返回主页。在阻止默认行为之前,请尝试检查元素是否存在。如果该元素不存在,浏览器将正常访问该链接。这是一种方法。

$(document).ready(function(){
    $('a.logo, ul.nav a, #mmenu a, a.mobileLogo').bind('click',function(event){
        var hash = '#' + $(this).attr('href').split('#')[1];

        // check if the element exists on your page
        if ($(hash).length) {
            // if so, scroll to it and prevent the default behavior
            $('html, body').stop().animate({
                scrollTop: $(hash).offset().top - 0
            }, 500);
            event.preventDefault();                
        }
    });
});
相关问题