我正在尝试优化从其他页面点击的锚标记的偏移量。我尝试将我的平滑滚动脚本与StackOverflow中另一篇文章的解决方案混合在一起,并想出了这个:
if ( window.location.hash ) scroll(0,0);
// void some browsers issue
setTimeout( function() { scroll(0,0); }, 1);
if ( window.location.hash ) {
$('html, body').animate({
scrollTop: $(window.location.hash).offset().top +75
}, 5);
}
// in-page anchors
$('a[href*=\\#]:not([href=\\#])').click(function() {
// if mobile menu is open, close it
if ($('#header-navigation.toggled').length) {
$('#header-navigation').removeClass('toggled');
}
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 -150
}, 500);
return false;
}
}
});
// more scripts follow...
但结果并不完美,特别是在IE中。我也不明白为什么偏移是页内锚点的负数,但是引用锚点的正数。我非常喜欢平滑滚动对于页内锚点的工作方式,所以我尝试重新加工:
//Set smooth scrolling for anchor tags
$('a[href*=\\#]:not([href=\\#])').click(function() {
// if mobile menu is open, close it
if ($('#header-navigation.toggled').length) {
$('#header-navigation').removeClass('toggled');
}
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) {
if ($('#coi-hq-submenu').length) {
// COI HQ needs higher offset for fixed submenu
$('html,body').animate({
scrollTop: target.offset().top -150
}, 500);
} else {
$('html,body').animate({
scrollTop: target.offset().top -50
}, 500);
}
return false;
}
}
});
// Offset anchors from referring pages
var referringTarget = window.location.hash;
if ( referringTarget ) {
if ($('#coi-hq-submenu').length) {
// COI HQ needs higher offset for fixed submenu
$('html,body').animate({
scrollTop: $(referringTarget).offset().top -150
}, 5);
} else {
$('html,body').animate({
scrollTop: $(referringTarget).offset().top -50
}, 5);
}
return false;
}
// more scripts follow...
这会完全抵消引用网址,但会返回false;阻止我的其余脚本工作。我试过(e)防止默认; (e)停止传播; - 但没有运气。如果我删除return false;完全,我得到一个完全不同的偏移。
我如何构造它以获得我想要的偏移量,但不能阻止其余的脚本工作?