【问题标题】:jquery to fix offsetting an html anchor to adjust for fixed header breaks modaljquery修复偏移html锚以调整固定标题中断模式
【发布时间】: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;
  }
}
});

当我使用这段代码时会出现两个问题:

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

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

    $(document).on('click','.navbar-collapse.in',function(e) { if( $(e.target).is('a') ) { $(this).collapse('toggle'); } });

所以我的问题是:在移动视图中单击锚标记后,我如何仍然使用此代码并防止它破坏我的模式,同时还使菜单折叠?

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

【问题讨论】:

    标签: javascript twitter-bootstrap


    【解决方案1】:

    我能够通过在被导航栏隐藏的锚点前面添加一个 mytext 来解决问题 1,然后将函数更改为仅查找以该特定文本开头的 id。

     $("a[href*='#mytext']:not([href='#'])").click(function() {
    

    所以此时唯一不起作用的是单击锚链接后菜单折叠。

    如何在函数本身中添加以下代码?

    $(document).on('click','.navbar-collapse.in',function(e) {
    if( $(e.target).is('a') ) {
        $(this).collapse('toggle');
    }
    });
    

    【讨论】:

      猜你喜欢
      • 2012-02-21
      • 1970-01-01
      • 2021-10-23
      • 2016-05-20
      相关资源
      最近更新 更多