javascript - Bootstrap .affix - jQuery hasClass 不工作

标签 javascript jquery twitter-bootstrap

我正在使用 Bootstrap .affix 插件,并且我试图在添加 Affix 类时对导航栏执行一些操作,但由于某种原因,一旦将其添加到导航栏,我似乎无法访问该类.

请记住,导航栏只是我创建的一个变量。

navbar.affix({
    offset: {
        top: header.height()
    }
});

上面的代码在滚动标题高度后将 .affix 类添加到我的导航栏,当我查看 Chrome 开发人员工具时,我肯定会看到该类已添加,但是当我尝试执行以下操作时:

navbar.hasClass('affix', function() { // Do something });

上面的代码永远不会被调用......就好像 .affix 永远不会添加到导航栏一样。

我在这里遗漏了什么吗?它是否在做一些我不知道的事情,以某种方式阻止我访问 .affix 类?

最佳答案

您不能将函数分配给 hasClass 方法。相反,使用基于 hasClass 结果的真/假条件来调用您的函数。

The .hasClass() method will return true if the class is assigned to an element ...

https://api.jquery.com/hasclass/

编辑:我已经使用navbar.attr('class')检查了哪个类被添加到元素中,结果是main-menu affix-顶部。因此,如果您检查 hasClass('affix-top') 它应该可以工作。 https://jsfiddle.net/yqy7gah6/14/

编辑2:您应该更好地检查这三个类中的任何一个是否存在,以确定已应用affix:以下是affix插件的工作原理:affix-topaffixaffix-bottom
您可以将 hasClassOR 一起使用,或者您可以更好地使用 jQuery is像这样:

if (navbar.is('.affix, .affix-top, .affix-bottom')) {
  // Do you stuff here
}

来自Bootstrap对Affix的描述:

  1. To start, the plugin adds .affix-top to indicate the element is in its top-most position. At this point no CSS positioning is required.
  2. Scrolling past the element you want affixed should trigger the actual affixing. This is where .affix replaces .affix-top and sets position: fixed; (provided by Bootstrap's CSS).
  3. If a bottom offset is defined, scrolling past it should replace .affix with .affix-bottom. Since offsets are optional, setting one requires you to set the appropriate CSS. In this case, add position: absolute; when necessary. The plugin uses the data attribute or JavaScript option to determine where to position the element from there.

关于javascript - Bootstrap .affix - jQuery hasClass 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33839287/

相关文章:

javascript - AngularJS。添加全局 AJAX 错误处理程序(如果尚未定义)

html - 如何根据媒体查询更改图像大小?

javascript - 如何在路由 Ember.js 中创建默认菜单

css - Font Awesome (4.0.3)+ bootstrap(3.0.0)+ asp.net : changing font family

jquery - 我们可以在 Web 应用程序中同时使用 jQuery 和 AngularJS 吗?

javascript - 输入焦点不起作用/无法选择单选按钮 - Bootstrap

javascript - 如何从jquery中的href值中删除#

javascript - 我怎样才能正确地将这个简单的 javascript 组合到这个小小的 php 片段中?

javascript - .html 中的 Jquery if 语句

javascript - 如何使用 jQuery 将点击监听器附加到动态创建的子元素?