关于锚点链接的偏移问题
2016-04-01 19:04
495 查看
用BOOSTRAP写页面的时候,用到了锚点链接
我们要让网页的位置再向下偏移一小段距离(原版在这里https://segmentfault.com/q/1010000000124208)。即
(1)在
(2)对于支持css3的:target声明可以这样:
或者直接给section设定一个类.section, 然后设定每个section的padidng-top值(设置marign-top没用噢,只能padding值,道理你懂的)。
(3)用jquery去调整scroll解决:
或者jquery的jquery-hashchange,绑定window.onhashchange事件:
<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(); });
相关文章推荐
- Web布局连载——两栏固定布局(五)
- [div+css]晒晒最新制作专题推广页模板
- 盒子模型
- CSS选择器
- CSS样式优先权
- [css] line-height 百分比单位和数值单位的区别
- Apple官网研究之使用Justify布局导航
- 设计更快的网页(三):字体和 CSS 调整
- 纯CSS制作的新闻网站中的文章列表
- 10条影响CSS渲染速度的写法与使用建议第1/3页
- BS项目中的CSS架构_仅加载自己需要的CSS
- 很不错的 CSS Hack 又学了一招
- 发一个css比较清爽的写法
- CSS expression控制图片自动缩放效果代码[兼容 IE,Firefox]
- css布局网页水平居中常用方法
- CSS经典技巧十则第1/2页
- css 兼容性问题this.style.cursor=''hand''
- IE6不能正常解析CSS文件问题的解决方法及原因分析
- 欲练CSS ,必先解决IE的一些细节分析
- CSS文字截取功能实现代码