我正在使用 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-top
、affix
和affix-bottom
。
您可以将 hasClass
与 OR
一起使用,或者您可以更好地使用 jQuery is
像这样:
if (navbar.is('.affix, .affix-top, .affix-bottom')) {
// Do you stuff here
}
来自Bootstrap对Affix的描述:
- 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.- 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).- 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/