JQuery Detect class changes

前端 未结 3 620
北荒
北荒 2020-12-05 10:41

I am using a plugin that added a class open to .slide-out-div when opened.

So I am trying to change some css if the open is detected.

相关标签:
3条回答
  • 2020-12-05 11:21

    There is no event of class-added, you will need to track it yourself...

    It can be done with an infinite loop with setTimeout to check if the class has changed.

    function checkForChanges()
    {
        if ($('.slide-out-div').hasClass('open'))
            $('.otherDiv').css('top','0px');
        else
            setTimeout(checkForChanges, 500);
    }
    

    You can call the function when you want, or onDOM ready:

    $(checkForChanges);
    
    0 讨论(0)
  • 2020-12-05 11:30

    The question's a bit old, but since I came across while looking for a similar problem, thought I'd share the solution I went with here - Mutation Observers

    In your case, I'd create a mutation observer

    var mut = new MutationObserver(function(mutations, mut){
      // if attribute changed === 'class' && 'open' has been added, add css to 'otherDiv'
    });
    mut.observe(document.querySelector(".slide-out-div"),{
      'attributes': true
    });
    

    The function in mutation observer is called any time an attribute of .slide-out-div is changed, so need to verify the actual change before acting.

    More details here on Mozilla's documentation page

    0 讨论(0)
  • 2020-12-05 11:41

    You can use attrchange jQuery plugin. The main function of the plugin is to bind a listener function on attribute change of HTML elements.

    Code sample:

    $("#myDiv").attrchange({
        trackValues: true, // set to true so that the event object is updated with old & new values
        callback: function(evnt) {
            if(evnt.attributeName == "class") { // which attribute you want to watch for changes
                if(evnt.newValue.search(/open/i) == -1) { // "open" is the class name you search for inside "class" attribute
    
                    // your code to execute goes here...
                }
            }
        }
    });
    
    0 讨论(0)
提交回复
热议问题