如果我在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解决方案,将在IE中工作:
假设导航栏元素是这样的:
<ul>
<li><a class="navigation" href="/#contact-us">Contact us</a></li>
<li><a class="navigation" href="/#about-us">About us</a></li>
</ul>
你可以使用下面的jquery片段来偏移滚动:
$(function() {
$("a.navigation").click(function(event) {
event.preventDefault();
offSetScroll($(this));
});
offSetScrollFromLocation(window.location.href.toLowerCase());
});
function offSetScroll(anchor) {
var href = anchor.attr("href");
offSetScrollFromLocation(href);
}
function offSetScrollFromLocation(href) {
//Change this according to the height of the navigation bar
var fromTop = 250;
if(href.indexOf("#")<=0)
return;
var hash=href.substring(href.indexOf("#"));
var targetOffset = $(hash).offset().top-fromTop;
$('html, body').animate({scrollTop: targetOffset}, 400, function(e) {
});
}
我发现处理这个问题的最好方法是(用固定的元素高度替换65px):
div:target {
padding-top: 65px;
margin-top: -65px;
}
如果你不喜欢使用目标选择器,你也可以这样做:
.my-target {
padding-top: 65px;
margin-top: -65px;
}
注意:如果目标元素的背景色与父元素的背景色不同,这个例子将不起作用。
例如:
<div style="background-color:red;height:100px;"></div>
<div class="my-target" style="background-color:green;height:100px;"></div>
在这种情况下,我的目标元素的绿色将覆盖65px的父元素红色。
我没有找到任何纯CSS解决方案来处理这个问题,但如果你没有另一个背景色,这个解决方案是最好的。
使用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,但另一个更受欢迎的问题因为这个问题而关闭了,我无法回答。