a标签锚点位置偏移(页面顶部有fix header) |
您所在的位置:网站首页 › 锚点移动 › a标签锚点位置偏移(页面顶部有fix header) |
写页面的时候,用到了锚点链接,但是发现点击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)在前面再加一个作为暗锚,将这个锚点进行偏移:(最直接的方法) .target-fix { position: relative; top: -60px; // 偏移为nav被fixed元素的高度 display: block; height: 0; //高度为0 overflow: hidden; } HTML: /*暗锚*/ /*正文div*/ (2)对于支持css3的:target声明可以这样:(需要现代浏览器支持,IE落后浏览器不支持) 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(); }); ———————————————— 版权声明:本文为CSDN博主「changreal」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/changreal/article/details/51039010 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |