我正在努力清理我的锚的工作方式。我有一个固定在页面顶部的标题,所以当你链接到页面其他地方的锚时,页面跳转,锚位于页面顶部,留下固定标题后面的内容(我希望这是有意义的)。我需要一种方法来抵消锚的25px从头部的高度。我更喜欢HTML或CSS,但Javascript也可以接受。
当前回答
你可以只使用CSS而不需要任何javascript。
给你的锚一个类:
<a class="anchor" id="top"></a>
然后,通过将锚定位为块元素并相对定位,您可以将锚定位在比它在页面上实际出现的位置更高或更低的偏移量。-250px将锚点向上定位250px
a.anchor {
display: block;
position: relative;
top: -250px;
visibility: hidden;
}
其他回答
我也在寻找这个问题的解决方案。对我来说,这很简单。
我有一个列表菜单与所有的链接:
<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;}
更改顶部值以匹配固定标题的高度(或更多)。 现在我认为这也适用于其他元素。
这将从以前的答案中提取许多元素并组合成一个微小的(194字节缩小)匿名jQuery函数。调整fixedElementHeight为您的菜单或块元素的高度。
(function($, window) {
var adjustAnchor = function() {
var $anchor = $(':target'),
fixedElementHeight = 100;
if ($anchor.length > 0) {
$('html, body')
.stop()
.animate({
scrollTop: $anchor.offset().top - fixedElementHeight
}, 200);
}
};
$(window).on('hashchange load', function() {
adjustAnchor();
});
})(jQuery, window);
如果你不喜欢这个动画,替换它
$('html, body')
.stop()
.animate({
scrollTop: $anchor.offset().top - fixedElementHeight
}, 200);
:
window.scrollTo(0, $anchor.offset().top - fixedElementHeight);
糟蹋版本:
!function(o,n){var t=function(){var n=o(":target"),t=100;n.length>0&&o("html, body").stop().animate({scrollTop:n.offset().top-t},200)};o(n).on("hashchange load",function(){t()})}(jQuery,window);
再加上Ziav的回答(感谢Alexander Savin),我需要使用老式的<a name="…">…</a> as we're using <div id="…">…</div>用于代码中的另一个目的。我在使用display: inline-block时遇到了一些显示问题——每个<p>元素的第一行都略微右缩进(在Webkit和Firefox浏览器上都是如此)。我最终尝试了其他的显示值和display: table-标题对我来说非常适合。
.anchor {
padding-top: 60px;
margin-top: -60px;
display: table-caption;
}
我的解决方案结合了CMS的目标和前选择器。其他技术不考虑锚中的文本。调整高度和负边距到你需要的偏移量…
:target::before {
content: '';
display: block;
height: 180px;
margin-top: -180px;
}
这是我们在网站上使用的解决方案。调整headerHeight变量,无论你的头部高度是什么。将js-scroll类添加到应该在单击时滚动的锚。
// SCROLL ON CLICK
// --------------------------------------------------------------------------
$('.js-scroll').click(function(){
var headerHeight = 60;
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top - headerHeight
}, 500);
return false;
});