我正在努力清理我的锚的工作方式。我有一个固定在页面顶部的标题,所以当你链接到页面其他地方的锚时,页面跳转,锚位于页面顶部,留下固定标题后面的内容(我希望这是有意义的)。我需要一种方法来抵消锚的25px从头部的高度。我更喜欢HTML或CSS,但Javascript也可以接受。
当前回答
这将从以前的答案中提取许多元素并组合成一个微小的(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);
其他回答
我遇到了同样的问题,最终手动处理点击事件,如下所示:
$('#mynav a').click(() ->
$('html, body').animate({
scrollTop: $($(this).attr('href')).offset().top - 40
}, 200
return false
)
当然,滚动动画是可选的。
@AlexanderSavin的解决方案在WebKit浏览器中对我来说很棒。
另外,我不得不使用:target伪类,它将样式应用到选定的锚来调整FF, Opera和IE9中的填充:
a:target {
padding-top: 40px
}
注意,这种风格不适合Chrome / Safari,所以你可能不得不使用css-hacks,条件注释等。
我还想注意到,Alexander的解决方案工作,因为目标元素是内联的。如果你不想要链接,你可以简单地改变显示属性:
<div id="myanchor" style="display: inline">
<h1 style="padding-top: 40px; margin-top: -40px;">My anchor</h1>
</div>
对于现代浏览器,只需将CSS3:target选择器添加到页面。这将自动应用于所有的锚。
:target {
display: block;
position: relative;
top: -100px;
visibility: hidden;
}
这是受到Shouvik回答的启发-与他的概念相同,只是固定头的大小没有硬编码。只要你的固定头在第一个头节点中,这应该“正常工作”。
/*jslint browser: true, plusplus: true, regexp: true */
function anchorScroll(fragment) {
"use strict";
var amount, ttarget;
amount = $('header').height();
ttarget = $('#' + fragment);
$('html,body').animate({ scrollTop: ttarget.offset().top - amount }, 250);
return false;
}
function outsideToHash() {
"use strict";
var fragment;
if (window.location.hash) {
fragment = window.location.hash.substring(1);
anchorScroll(fragment);
}
}
function insideToHash(nnode) {
"use strict";
var fragment;
fragment = $(nnode).attr('href').substring(1);
anchorScroll(fragment);
}
$(document).ready(function () {
"use strict";
$("a[href^='#']").bind('click', function () {insideToHash(this); });
outsideToHash();
});
你可以只使用CSS而不需要任何javascript。
给你的锚一个类:
<a class="anchor" id="top"></a>
然后,通过将锚定位为块元素并相对定位,您可以将锚定位在比它在页面上实际出现的位置更高或更低的偏移量。-250px将锚点向上定位250px
a.anchor {
display: block;
position: relative;
top: -250px;
visibility: hidden;
}