在stackoverflow看到的一个方法是在主体内容前加一个暗锚:
代码如下 |
复制代码 |
<a class="target-fix" name="a-<?php $a->id(); ?>"></a>
<artivle>主体内容...</article>
|
将锚点进行偏移,并隐藏占位:
代码如下 |
复制代码 |
.target-fix {
position: relative;
top: -44px; // 偏移值
display: block;
height: 0;
overflow: hidden;
}
|
这个也是最直接的方法。
我采用的是相对简洁的方法:对于现代浏览器如果支持css的:target声明,可以这么设置:
代码如下 |
复制代码 |
article.a-post:target{
padding-top:44px;
}
|
对于IE这等落后的浏览器是不支持的.另外可以使用js去调整scroll,比如使用jQuery:
代码如下 |
复制代码 |
$(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-hashchange:https://github.com/cowboy/jquery-hash...
绑定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();
});
|
关于window.onhashchange事件:https://developer.mozilla.org/en-US/d... |