[英]jquery to fix offsetting an html anchor to adjust for fixed header breaks modal
我的锚链接隐藏在引导程序3的固定顶部导航栏下时遇到问题,我喜欢Shouvik在这里建议的解决方案:
但是,尽管以下代码完美地解决了该问题,但它打破了其他一些问题。
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('切换');}});
所以我的问题是:在移动视图中单击定位标记后,如何仍能使用此代码并防止其破坏我的模态,同时使菜单折叠?
我可以让上面的代码忽略我的特定模式锚链接吗?
通过在导航栏隐藏的锚点之前添加mytext,然后将功能更改为仅查找以该特定文本开头的id,我可以解决问题1。
$("a[href*='#mytext']:not([href='#'])").click(function() {
因此,此时唯一不起作用的是单击锚链接后菜单崩溃。
如何在函数本身中添加以下代码?
$(document).on('click','.navbar-collapse.in',function(e) {
if( $(e.target).is('a') ) {
$(this).collapse('toggle');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.