使用jQuery检查元素是否一直有类 [英] Using jquery to check if element has class constantly

查看:95
本文介绍了使用jQuery检查元素是否一直有类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用stickyJS在我的wordpress网站上创建一个粘性标头.我已经正确地将脚本排入队列,并且粘性工作正常.

I'm using stickyJS to create a sticky header with my wordpress website. I have enqueued the scripts properly and the sticky is working perfectly.

我要实现的目标是不断检查为粘性设置的nav元素是否具有称为"is-sticky"的类,如果是,则更改一些CSS.

What I am trying to achieve is to constantly check if the nav element that I have set up for the sticky has a class called "is-sticky" and if so change some of the CSS.

这是我已经拥有的代码:

Here is the code that I have already:

function stickyInit($)
{
$("#site-navigation").sticky({topSpacing:0});

window.setInterval(check_sticky,500);

function check_sticky(){
    if($("#site-navigation-sticky-wrapper").hasClass("is-sticky")){
        console.log ("Do Something");
    }
}
}

jQuery(document).ready(function ($) {
stickyInit($);
});

这是我已排队将导航设置为粘性的所有文件中的代码.

This is all the code in the file that I have enqueued to set the nav as sticky.

如您所见,我已经使用setInterval尝试创建一个循环以不断测试#site-navigation-sticky-wrapper"元素以查看其是否具有上述类.

As you can see I have used setInterval to try and create a loop to constantly test the "#site-navigation-sticky-wrapper" element to see if it has the class mentioned above.

此代码有效,我在Firebug控制台中收到了消息,但我只收到一次,而不是反复收到.

This code works and I get the message in firebug console, but I only ever get it once instead of repeatedly.

所以我的问题是,如何不断测试此元素以查看其是否具有"is-sticky"类,以便在出现该问题时可以替换nav css?

So my question is, how do I constantly test this element to see if it has the class "is-sticky" so I can alternate the nav css when it does?

当元素上未设置"is-sticky"类时(在我滚动回到顶部之后),如何将导航设置回其原始位置?还是会这样做呢?

Also when the class "is-sticky" isnt set on the element (after I have scrolled back to the top) how do I set the nav back to its original position? Or will it just do that anyway?

推荐答案

检查此小提琴-反复触发当粘滞"类处于活动状态时&滚动到停止位置时,导航位置会自动恢复到以前的状态.

Check this fiddle - it fires repeatedly when the 'is-sticky' class is active & the nav position is automatically restored to its former state when you scroll to the stop.

// Your code
function stickyInit($){

    $("#site-navigation").sticky({topSpacing:0});

        function check_sticky(){
            if ( $("#site-navigation-sticky-wrapper").hasClass("is-sticky") ) {
                console.log ("Do Something");
            }
        }

    window.setInterval(check_sticky,500);
}

jQuery(document).ready(function ($) {

    stickyInit($);

});

这篇关于使用jQuery检查元素是否一直有类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆