在jQuery中,当dom更改时,如何触发函数?

在jQuery中,当dom更改时,如何触发函数?,jquery,html,css,function,dom,Jquery,Html,Css,Function,Dom,我正在使用一个jQuery插件,它在文本中添加了背景——暗背景——复杂类,以将文本与背景进行对比,例如,在滚动到背景——浅背景——复杂的过程中,这种情况发生了变化。我需要将类添加到覆盖id(多佛=暗覆盖)(nover=无覆盖)(lover=亮覆盖),这取决于插件添加到文本中的类。我对jQuery真的不是很在行,我不是要求你代替我去做,但你会帮我省去很多麻烦,我会更好地理解它 jQuery(document).ready(function(){ if(jQuery( "#globalte

我正在使用一个jQuery插件,它在文本中添加了背景——暗背景——复杂类,以将文本与背景进行对比,例如,在滚动到背景——浅背景——复杂的过程中,这种情况发生了变化。我需要将类添加到覆盖id(多佛=暗覆盖)(nover=无覆盖)(lover=亮覆盖),这取决于插件添加到文本中的类。我对jQuery真的不是很在行,我不是要求你代替我去做,但你会帮我省去很多麻烦,我会更好地理解它

jQuery(document).ready(function(){

    if(jQuery( "#globaltext" ).hasClass( "background--dark background--complex" )){
        jQuery( "#overlay" ).addClass( "dover" );
    }else{
        jQuery( "#overlay" ).addClass( "nover" );
    }
});
我有另一个解决办法。 您不需要jQuery,只需要足够的javascript

HTML:

<div id="classList">my Colors</div>

<button onclick="changeClass('red')">red</button>
<button onclick="changeClass('blue')">blue</button>
<button onclick="changeClass('yellow')">yellow</button>
对于javascript第1部分:创建EventListener

// create custom EventListener for just attribute
function attributeEventListener(target, attr, fun){
  target = document.querySelector(target);

  var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      // just looking for our attribute
      if (mutation.attributeName == attr){
        fun();
      }
    });    
  });

  // configuration of the observer:
  //just looking for attributes
  var config = {attributes: true};

  // pass in the target node, as well as the observer options
  observer.observe(target, config);
}
第2部分-您需要像这样使用它:

new attributeEventListener('#classList','class', function(){
  console.log('changed ...');
});
// first parameter is target (css selector)
// second parameter is attribute name (for your case is class)
// third parameter is your function when event called ...
第3部分-更改类别

function changeClass(color){
      var target = document.getElementById('classList');
      if (target.className != color)
        target.className = color; 
    }
在此处查看我的代码

变异观察者文档:


Broswer支持:只是现代浏览器支持mutationobserver

需要更多细节。您发布的代码不会更改DOM。它检查globaltext是否有一个类,然后执行一些操作。您在哪里更改DOM?您希望触发什么事件?在@garek007中,DOM更改发生在该文件中。我正在寻找一个类似于MutationObserver的解决方案,但我无法运行。[链接]()我需要更多的信息。我无法通读那个文件来找出你需要什么。你能解释一下你想做什么以及所有涉及的步骤吗?@garek007插件在#globaltext中添加了背景——暗背景——复杂,背景——浅背景——复杂的类。我已经做了一个覆盖div上面的背景图像与3类,多佛,情人,nover。我需要一个解决方案来检查#globaltext上的当前类是background--暗背景--复杂还是background--浅背景--复杂,这取决于将.dover/.lover/.nover添加到#覆盖中。插件需要几秒钟才能识别add类,我发布的代码会立即启动。监视div更改的东西。那么您上面发布的代码是否适合您?第二,您需要在添加“dover”或“nover”类后启动一个函数吗?
function changeClass(color){
      var target = document.getElementById('classList');
      if (target.className != color)
        target.className = color; 
    }