如大家在 segmentfault 当前版本所见到的,点击锚点链接后,展示的内容会因为 header 区的浮动而被遮盖。
本人在做HAMdb数据库的时候也发现顶部affix导航之后,点击锚点会使得其导航被fixed,导致被target的正文会以窗口顶部对其,导致如图所示的遮挡。
查阅了许多资料,并且做了很多尝试都失败了。总体来说:
- 在<content>前面再加一个<a class="target-fix"></a>作为暗锚,将这个锚点进行偏移:
1234567target-fix {position: relative;top: -60px; // 偏移为nav被fixed元素的高度display: block;height: 0; //高度为0overflow: hidden;} - 对于支持CSS3的:target声明可以这样:
123article.a-post:target{padding-top:44px;} - 用jQuery去调整scroll解决:
1234567891011$(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事件:
1234567891011121314$(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();});
本人在尝试上述方法后,基本没解决。可能是由于其他冲突或者什么原因。最终决定自己来实现:
首先,贴出<a>部分:
1 2 3 4 5 6 7 8 9 10 11 |
<div class="well" id="myNav" style="padding: 5px; text-align: center;"> <div class="btn-group" role="group" aria-label="Justified button group"> <a href="#Identification" class="btn btn-primary" role="button">Identification</a> <a href="#Properties" class="btn btn-primary" role="button">Physicochemical Properties</a> <a href="#Autophagy" class="btn btn-primary" role="button">Role in Autophagy</a> <a href="#Biological" class="btn btn-primary" role="button">Biological Behaviors</a> <a href="#Links" class="btn btn-primary" role="button">External Links</a> <a href="#References" class="btn btn-primary" role="button">References</a> </div> </div> |
然后,贴出<content>部分:
1 2 3 4 5 6 7 8 9 10 |
<table id="info" class="info_table table table-condensed table-striped"> {% if all_chemical_list %} <tr id="Identification"><td class="divider" colspan="2" >Identification</td></tr> <tr> <th style="width: 128px;">Chemical Name</th> <td>{{ all_chemical_list.Chemical_Name }}</td> </tr> <tr> </table> |
最后,贴出javascript部分:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
$('#myNav').affix({ offset: { top: 100,//滚动中距离页面顶端的位置 bottom: function () {//滚动完成时距离页面底部的位置 return (this.bottom = $('footer').outerHeight(true)) } } }); $('.btn-group a').click(function(){ var ps = $($(this).attr('href')).offset().top-50; $('html,body').delay(100).animate({scrollTop:ps}, 300) }); |
第一部分是启动affix的代码,米有什么好解释。第二段第一句找到当前content所在位置,并且下移50px;第二句,在affix执行后延迟一段时间,然后将整个content下移。这个延迟主要是为了避免屏幕在两种位置瞬间闪烁。
这种效果还是在一定程度上更好,前几种要么要引入新的js,导致冲突,要么不兼容。个人感觉自己的方法比较完美达到想要效果。
本文原始地址:https://www.ifyoung.net/javascript-affix.html
本站所有文章,若标明本站原创,转载请注明出处来自https://www.ifyoung.net/
暂无评论