Javascript 从另一页单击时,偏移滚动到定位标记
我正在尝试优化从另一个页面单击的锚标记的偏移量。我尝试将我的平滑滚动脚本与StackOverflow中另一篇文章中的解决方案混合,并得出以下结论:Javascript 从另一页单击时,偏移滚动到定位标记,javascript,jquery,smooth-scrolling,Javascript,Jquery,Smooth Scrolling,我正在尝试优化从另一个页面单击的锚标记的偏移量。我尝试将我的平滑滚动脚本与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({
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...
这完全抵消了引用URL,但返回false;阻止我的其余脚本工作。我试图(e)防止违约;和(e)停止传播;-但是没有运气。如果我删除返回错误;完全地,我得到了一个完全不同的偏移量
如何构造该脚本以获得所需的偏移量,但又不阻止其余脚本工作