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

关于锚点链接的偏移问题

2016-04-01 19:04 495 查看
用BOOSTRAP写页面的时候,用到了锚点链接
<a href="#section1"></a>
,但是发现点击a到对应的section的时候,不能到section的上面,会到section中的某个位置,一开始我以为是元素内容部的margin或者h1的问题,后来通过console.log()输出高度等发现了原因:最上面的nav 加了属性position:fixed的原因———虽然元素被fixed在最上面了,可是页面计算section的页边距top的时候还是把nav的高度算上去了,所以点击锚点链接的时候,偏移的距离是section页边距的高度加上nav的高度( section.offset().top + nav.height)。解决方法如下:

我们要让网页的位置再向下偏移一小段距离(原版在这里https://segmentfault.com/q/1010000000124208)。即

(1)在
<section>
前面再加一个
<a class="target-fix">
作为暗锚,将这个锚点进行偏移:

.target-fix {
position: relative;
top: -60px; // 偏移为nav被fixed元素的高度
display: block;
height: 0; //高度为0
overflow: hidden;
}。


(2)对于支持css3的:target声明可以这样:

article.a-post:target{
padding-top:44px;
}


或者直接给section设定一个类.section, 然后设定每个section的padidng-top值(设置marign-top没用噢,只能padding值,道理你懂的)。

(3)用jquery去调整scroll解决:

$(function(){
if(location.hash){
var target = $(location.hash);
if(target.length==1){
var top = target.offset().top-44;
if(top > 0){
$('html,body').animate({scrollTop:top}, 1000);
}
}
}
});


或者jquery的jquery-hashchange,绑定window.onhashchange事件:

$(function(){
/* 绑定事件*/
$(window).hashchange(function(){
var target = $(location.hash);
if(target.length==1){
var top = target.offset().top-44;
if(top > 0){
$('html,body').animate({scrollTop:top}, 1000);
}
}
});
/* 触发事件 */
$(window).hashchange();
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  css