jquery - 脚本未执行

标签 jquery css twitter-bootstrap

我对网络语言的经验很少,所以这可能是一个简单的错误。

我有一个带有内部链接的网页,如 <a href="#div-id">button</a> .然而,由于响应式 Bootstrap 菜单,滚动有时会过度。问题与上一个问题中描述的完全一样,我尝试实现公认的解决方案:

How can I use HTML ID links with the Bootstrap navbar-header?

但是,建议的功能永远不会执行。我已经实现如下。作为一种万无一失的测试方法,我包含了两个警报语句(一个用于不相关的功能)。第一个警报语句正确执行,第二个警报语句从未执行。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script>
$(function () {                      // on document ready
    var div = $('#showOrHideDiv');   // cache <div>
    $('#action').click(function () { // on click on the `<a>`
        alert('here');               // => PROPERLY EXECUTED
        div.fadeToggle(1000);        // toggle div visibility over 1 second
    });
    // listen for click events originating from elements with href starting with #
    $('body').on('click.scroll-adjust', '[href^="#"]', function (e) {
      alert('here');                 // => NEVER EXECUTED
      var $nav;

      // make sure navigation hasn't already been prevented
      if ( e && e.isDefaultPrevented() ) return

      // get a reference to the offending navbar
      $nav = $('div.navbox')

      // check if the navbar is fixed
      if ( $nav.css('position') !== "fixed" ) return

      // listen for when the browser performs the scroll
      $(window).one('scroll', function () {
        // scroll the window up by the height of the navbar
        window.scrollBy(0, -$nav.height())
      });

    });
});

</script>

谁能指出我实现中的错误?

最佳答案

事实证明,还有其他我不知道的函数被调用(感谢 Jason 的提示)。这些脚本确保了平滑滚动,这是我使用的模板类型的一个共同特征,因此在这里给出我的解决方案可能会有用。

最后,我通过向与我自己尝试实现的函数类似的现有函数添加几行代码,解决了这个问题。

这是新代码,在我添加代码的地方有注释:

$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
  var target = $(this.hash);

  /* added by me: */
  var $x;
  var $nav;

  $nav = $('nav#tf-menu')

  if ( $nav.css('position') == "fixed" ){ $x=0; } else {$x=$nav.height()+30};
  /* end added */

  target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
  if (target.length) {
    $('html,body').animate({

      scrollTop: target.offset().top - 70 - $x //added the -$x
    }, 1000);
    return false;
  }
}
});
}

关于jquery - 脚本未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41944465/

相关文章:

jquery - 为什么 jQuery 不使用 $ ("form :input[name="some_input"]).val(); 更新输入值

javascript - 如果某些 dom 节点 float : left or they go down to a new line?,我如何用 javascript 判断

javascript - 如何在不使用 JS 中的 ID 的情况下通过类名更改元素的样式属性?

jquery - 如何从 csv 文件制作带有 highcharts 的图表?

javascript - 如何使用 Jquery 检查页面上是否存在链接?

jquery - 图像 block 问题内的图像比例

java - CSS类在父jsp加载时消失

twitter-bootstrap - 用于删除确认 mvc 的 Bootstrap 模式

html - 悬停转换 CSS 中的抖动

css - Form-horizo​​ntal 将 form-group 拉到右边