jquery修复抵消html锚点以调整固定的标题符休息模式

时间:2014-10-16 01:06:58

标签: javascript twitter-bootstrap

我的锚链接隐藏在bootstrap 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;
  }
}
});

使用此代码时会出现两个问题:

  1. 这会破坏我的模态,因为它引用了href标记中的任何哈希值。例如:#myModal链接不再打开。

  2. 在移动视图中,单击链接后不再关闭菜单。这个问题最初是由下面的脚本解决的,当我实现上述内容时,该脚本不再有效。

    $(document).on('click','。navbar-collapse.in',function(e){ if($(e.target).is('a')){     $(本).collapse( '切换'); } });

  3. 所以我的问题是:如何在移动视图中点击锚标记之后仍然使用此代码并防止它破坏我的模态同时使菜单崩溃?

    我可以让上面的代码忽略我的特定模态锚链接吗?

1 个答案:

答案 0 :(得分:0)

我能够通过在导航栏隐藏的锚点前添加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');
}
});
相关问题