【发布时间】:2014-10-16 01:06:57
【问题描述】:
我的锚链接隐藏在引导程序 3 中的固定顶部导航栏下时遇到问题,我喜欢 Shouvik 在这里建议的解决方案:
offsetting an html anchor to adjust for fixed header
然而,虽然下面的代码完美地解决了这个问题,但它破坏了其他一些问题。
function scrollToAnchor() {
if($(".jquery-anchor").length > 0 && document.URL.indexOf("#") >= 0){
var anchor = document.URL.split("#")[1];
$(".jquery-anchor").each(function() {
if($(this).attr("name") == anchor) {
$("html,body").animate({
scrollTop: $(this).offset().top - 50},
'slow');
}
});
}
}
$(function() {
$('a[href*=#]:not([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) {
$('html,body').animate({
scrollTop: target.offset().top - 30 //offsets for fixed header
}, 1000);
return false;
}
}
});
//Executed on page load with URL containing an anchor tag.
if($(location.href.split("#")[1])) {
var target = $('#'+location.href.split("#")[1]);
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 30 //offset height of header here too.
}, 1000);
return false;
}
}
});
当我使用这段代码时会出现两个问题:
这会破坏我的模式,因为它引用了 href 标记中的任何哈希值。例如:#myModal 链接不再打开。
-
在移动视图中,单击链接后不再关闭菜单。这个问题最初是由下面的脚本解决的,当我实现上述时不再起作用。
$(document).on('click','.navbar-collapse.in',function(e) { if( $(e.target).is('a') ) { $(this).collapse('toggle'); } });
所以我的问题是:在移动视图中单击锚标记后,我如何仍然使用此代码并防止它破坏我的模式,同时还使菜单折叠?
我可以让上面的代码忽略我的特定模式锚链接吗?
【问题讨论】:
标签: javascript twitter-bootstrap