如果我在HTML页面中有一个非滚动头,固定在顶部,有一个定义的高度:
是否有一种方法可以使用URL锚(#fragment部分)让浏览器滚动到页面中的某一点,但仍然尊重固定元素的高度,而不需要JavaScript的帮助?
http://example.com/#bar
WRONG (but the common behavior): CORRECT:
+---------------------------------+ +---------------------------------+
| BAR///////////////////// header | | //////////////////////// header |
+---------------------------------+ +---------------------------------+
| Here is the rest of the Text | | BAR |
| ... | | |
| ... | | Here is the rest of the Text |
| ... | | ... |
+---------------------------------+ +---------------------------------+
我在这里和其他地方的许多答案都遇到了很多麻烦,因为我的书签锚是FAQ页面中的部分标题,所以抵消标题并没有帮助,因为其余的内容只是停留在原地。所以我想我应该发帖。
我最终做的是几个解决方案的组合:
CSS:
.bookmark {
margin-top: -120 px;
padding-bottom: 120 px;
显示:块;
}
其中“120px”是你的固定标题高度(可能加上一些边距)。
书签链接HTML:
<a href="#01">你的常见问题是什么来着?< / >
书签内容HTML:
<span class="bookmark" id="01"></span>
你的常见问题是什么来着?< / h3 >
<p>一些常见问题的文本,后面跟着
< p >…</p>
这个解决方案的优点是span元素不仅隐藏,而且本质上是折叠的,不会填充您的内容。
我不能对这个解决方案有太多的功劳,因为它来自不同的资源,但它最适合我的情况。
你可以在这里看到实际的结果。
我已经很容易地使用CSS和HTML,使用上面提到的“锚:之前”方法。我认为它是最好的,因为它不会在你的divs之间产生大量的填充。
.anchor:before {
content:"";
display:block;
height:60px; /* fixed header height*/
margin:-60px 0 0; /* negative fixed header height */
}
这似乎并不适用于页面上的第一个div,但你可以通过添加填充到第一个div。
#anchor-one{padding-top: 60px;}
这里有一个工作小提琴:http://jsfiddle.net/FRpHE/24/
CSS技巧将是一个解决方案。使用jQuery可以实现一个适用于所有场景的解决方案。
参考https://codepen.io/pikeshmn/pen/mMxEdZ
方法:我们使用document.getElementById('header').offsetHeight获取固定导航的高度
并将滚动偏移到这个值。
var jump=function(e){
e.preventDefault(); //prevent "hard" jump
var target = $(this).attr("href"); //get the target
//perform animated scrolling
$('html,body').animate(
{
scrollTop: $(target).offset().top - document.getElementById('header').offsetHeight - 5 //get top-position of target-element and set it as scroll target
},1000,function() //scrolldelay: 1 seconds
{
location.hash = target; //attach the hash (#jumptarget) to the pageurl
});
}
$(document).ready(function()
{
$('a[href*="#"]').bind("click", jump); //get all hrefs
return false;
});
注:
它包含了头部和目标之间5个像素的差异
滚动效果不硬,比较平滑;平滑滚动