如果我在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 |
| ... | | ... |
+---------------------------------+ +---------------------------------+
使用jQuery的最小侵入性方法:
链接:
<a href="#my-anchor-1" class="anchor-link">Go To Anchor 1</a>
内容:
<h3 id="my-anchor-1">Here is Anchor 1</a>
脚本:
$(".anchor-link").click(function() {
var headerHeight = 120;
$('html, body').stop(true, true).animate({
scrollTop: $(this.hash).offset().top - headerHeight
}, 750);
return false;
});
通过将锚链接类分配给链接,其他链接(如手风琴或制表符控件)的行为不会受到影响。
这个问题不需要javascript,但另一个更受欢迎的问题因为这个问题而关闭了,我无法回答。
我之所以使用这种方法,是因为出于某种原因,其他提出的解决方案都不适合我。我保证我尽力了。
section {
position: relative;
border-top: 52px solid transparent; /* navbar height +2 */
margin: -30px 0 0;
-webkit-background-clip: padding-box;
-moz-background-clip: padding;
background-clip: padding-box;
}
section:before {
content: "";
position: absolute;
top: -2px;
left: 0;
right: 0;
border-top: 2px solid transparent;
}
如果您愿意,可以将section替换为类。
来源:跳转链接和视口定位
在Firefox 45和Chrome 52上测试。
引导版本:3.3.7
对于那些不相信我的人,我善意地准备了一个jsfiddle的解决方案:解决方案
我在这里和其他地方的许多答案都遇到了很多麻烦,因为我的书签锚是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元素不仅隐藏,而且本质上是折叠的,不会填充您的内容。
我不能对这个解决方案有太多的功劳,因为它来自不同的资源,但它最适合我的情况。
你可以在这里看到实际的结果。