我正在努力清理我的锚的工作方式。我有一个固定在页面顶部的标题,所以当你链接到页面其他地方的锚时,页面跳转,锚位于页面顶部,留下固定标题后面的内容(我希望这是有意义的)。我需要一种方法来抵消锚的25px从头部的高度。我更喜欢HTML或CSS,但Javascript也可以接受。
当前回答
我也在寻找这个问题的解决方案。对我来说,这很简单。
我有一个列表菜单与所有的链接:
<ul>
<li><a href="#one">one</a></li>
<li><a href="#two">two</a></li>
<li><a href="#three">three</a></li>
<li><a href="#four">four</a></li>
</ul>
下面是标题。
<h3>one</h3>
<p>text here</p>
<h3>two</h3>
<p>text here</p>
<h3>three</h3>
<p>text here</p>
<h3>four</h3>
<p>text here</p>
现在,因为我在页面顶部有一个固定的菜单,我不能让它去我的标签,因为它会在菜单后面。
相反,我在标签中放入了一个span标签,并带有正确的id。
<h3><span id="one"></span>one</h3>
现在使用2行CSS来正确定位它们。
h3{ position:relative; }
h3 span{ position:absolute; top:-200px;}
更改顶部值以匹配固定标题的高度(或更多)。 现在我认为这也适用于其他元素。
其他回答
不要使用固定位置的导航条,它覆盖了页面的其余内容(整个页面主体都是可滚动的),而是考虑使用静态导航条的不可滚动主体,然后将页面内容放在绝对位置的可滚动div中。
也就是说,有这样的HTML…
<div class="static-navbar">NAVBAR</div>
<div class="scrollable-content">
<p>Bla bla bla</p>
<p>Yadda yadda yadda</p>
<p>Mary had a little lamb</p>
<h2 id="stuff-i-want-to-link-to">Stuff</h2>
<p>More nonsense</p>
</div>
... 和CSS是这样的:
.static-navbar {
height: 100px;
}
.scrollable-content {
position: absolute;
top: 100px;
bottom: 0;
overflow-y: scroll;
width: 100%;
}
然而,这种方法有一个显著的缺点,那就是当页面标题中的元素被聚焦时,用户将无法使用键盘滚动页面(例如,通过向上和向下箭头或page up和page down键)。
下面是一个演示这个操作的JSFiddle。
我找到了这个解决方案:
<a name="myanchor">
<h1 style="padding-top: 40px; margin-top: -40px;">My anchor</h1>
</a>
这不会在内容和锚链接中产生任何差距,效果非常好。
我也曾面临过类似的问题,不幸的是,在实施了上述所有解决方案后,我得出了以下结论。
我的内部元素有一个脆弱的CSS结构和实现位置相对/绝对发挥,完全打破了页面设计。 CSS不是我的强项。
我写了这个简单的滚动js,它解释了由于标题引起的偏移,并将div重新定位到下面大约125像素。请用你认为合适的。
HTML
<div id="#anchor"></div> <!-- #anchor here is the anchor tag which is on your URL -->
JavaScript
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
&& location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 125 //offsets for fixed header
}, 1000);
return false;
}
}
});
//Executed on page load with URL containing an anchor tag.
if($(location.href.split("#")[1])) {
var target = $('#'+location.href.split("#")[1]);
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 125 //offset height of header here too.
}, 1000);
return false;
}
}
});
点击这里查看实时实现。
这对我来说很管用:
[id]::before {
content: '';
display: block;
height: 75px;
margin-top: -75px;
visibility: hidden;
}
用可链接id来提供导航栏高度的隐藏span标签怎么样?
#head1 {
padding-top: 60px;
height: 0px;
visibility: hidden;
}
<span class="head1">somecontent</span>
<h5 id="headline1">This Headline is not obscured</h5>
这里是小提琴:http://jsfiddle.net/N6f2f/7