使用主导航滚动网站问题

Scrolling Site Issues With Main Nav

本文关键字:网站 问题 滚动 导航      更新时间:2023-09-26

我为我的网站建立了一个滚动主页,用户可以点击标题中的链接向下滚动到网站的不同部分。我还有指向新页面的外部链接,允许用户查看不同的项目
不管出于什么原因,它都很好用,但一旦我到达其中一个项目页面,然后尝试单击主页或工作链接,它就无法正常工作。不创建第二个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,使其在外部页面上工作,有什么想法吗?

听起来#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();                
        }
    });
});