这应该是一个非常基本的问题,但是我早上的大部分时间都在解决这个问题,此时我已经接近认输了。我什至没有一点 js foo ——但我发现了一段注释很好的代码,我希望用它来动画锚链接:
$(document).ready(function() {
$('a[href*=#]').bind('click', function(e) {
e.preventDefault(); //prevent the "normal" behaviour which would be a "hard" jump
var target = $(this).attr("href"); //Get the target
var scrollToPosition = $(target).offset().top;
// perform animated scrolling by getting top-position of target-element and set it as scroll target
$('html, body').stop().animate({ scrollTop: scrollToPosition}, 600, function() {
location.hash = target; //attach the hash (#jumptarget) to the pageurl
});
return false;
});
});
我试图让它在 offset().top 上方 30px 处着陆——我试过了
$('html, body').stop().animate({ scrollTop: scrollToPosition -30}, 600,
这几乎可以奏效——它去了正确的地方,但随后又反弹回来。
我也试过
scrollTop: $(target).offset().top - 20 },
我也试过
scrollTop: $(hash).offset().top + $('#access').outerHeight()
这似乎并没有改变任何东西。
似乎答案可能在这里:JQuery page scroll issue with fixed header 但我似乎不太明白。
我知道这与其他问题类似——但我已经完成了我能找到的内容,而且我是文盲,无法复制/粘贴任何可以解决问题的内容。
我会非常感谢一个解决方案。
非常感谢,
马丁
附言
我发现的另一段代码确实有效,但它正在剥离主题标签,这使得它几乎无用。
$(function(){
$('a[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) {
var targetOffset = $target.offset().top;
$('html,body').animate({scrollTop: targetOffset - 30}, 1000);
return false;
}
}
});
});