关于使用固定导航a标签跳锚点时产生问题的解决方法

本文介绍了解决网页中导航栏固定头部时,使用a标签进行锚点跳转产生的偏移问题的方法,并提供了适用于当前页面及跨页面跳转的JavaScript代码实现。

1、导航固定在头部,a标签跳锚点时,偏移问题。

只适用于在当前页面内的锚点跳转

html部分代码:

<ul class="nav">
     <li class="dropdown action">
         <a data-ajax="false" href="index.php" class="dropdown-toggle">网站首页</a>
     </li>
     <li class="dropdown">
       <a data-ajax="false" onclick="goto(this)" href="index.php#aboutUs" class="dropdown-toggle" name="#aboutUs">关于我们</a>
      </li>
</ul>

js部分代码:

function goto(th){
    var divName = $(th).attr("name");
    if( divName == '#aboutUs'){
       $("html, body").animate({scrollTop: $(divName ).offset().top - 100 + "px"}, 100);
    }else{
       $("html, body").animate({scrollTop: $(divName ).offset().top - 68 + "px"}, 100);
    }
}

2、跨页面–a标签跳锚点时,偏移问题。

$(function(){
    $(window).hashchange(function(){
        var hash = $(location.hash);
        if( hash.selector == '#aboutUs'){
            $("html, body").animate({scrollTop: $(hash.selector).offset().top - 100 + "px"}, 100);
        }else{
            $("html, body").animate({scrollTop: $(hash.selector).offset().top - 68 + "px"}, 100);
        }
    });
    $(window).hashchange();
})
function goto(th){
    var divName = $(th).attr("name");
    hashA();
}
function hashA(){
    var hash = window.location.hash;
    if( hash == '#aboutUs'){
        $("html, body").animate({scrollTop: $(hash).offset().top - 100 + "px"}, 100);
    }else{
        $("html, body").animate({scrollTop: $(hash).offset().top - 68 + "px"}, 100);
    }
}

注:

  • 之前不写$(window).hashchange();时,每次都是获取到的是上一次点击之后的hash值。应该是执行顺序的问题,不明白怎么在点击事件完成之后,执行函数,所以才用了这种方式。
  • 代码具体应用时,具体问题具体分析。

希望有同学们看到之后可以解答,感谢。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值