您的位置:首页 > Web前端 > JavaScript

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

2017-06-30 10:37 351 查看

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值。应该是执行顺序的问题,不明白怎么在点击事件完成之后,执行函数,所以才用了这种方式。

代码具体应用时,具体问题具体分析。

希望有同学们看到之后可以解答,感谢。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  html js
相关文章推荐