使用Jquery观察属性更改

Watch attribute changes with Jquery

本文关键字:属性 观察 Jquery 使用      更新时间:2023-09-26

当div的属性发生变化时,我需要触发一个事件。我偶然发现了这个插件http://meetselva.github.io/attrchange/它似乎起到了作用。唯一的问题是它多次触发事件。例如,如果我这样做:

$("#sgPluginBox").attrchange({
    callback: function(evnt) {
        if(evnt.attributeName == "style") { 
            alert('test');
        }
    }
});

它将显示八个警告框。我不知道它为什么这么做。当样式属性更改时,我需要它只显示一个警告框。有什么建议吗?

编辑:

这不是最优雅的解决方案,但看起来使用$.one(alert('test'))就成功了。

尝试使用MutationObserver

$(document).ready(function() {
  var target = $("#test").get(0);
  // create an observer instance
  var observer = new MutationObserver(function(mutations) {
    if (mutations.length) {
      alert(mutations[0].attributeName + " changed")
      target.innerHTML = target.style.fontSize;
      // disconnect `observer`
      this.disconnect()
    }
  });
  // configuration of the observer:
  var config = {
    attributes: true
  };
  // pass in the target node, as well as the observer options
  observer.observe(target, config);
  $("#test").attr("style", "font-size:36px");
  setTimeout(function() {
      $("#test").attr("style", "font-size:52px")
      .html($("#test").css("fontSize"))
    },
    1000)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="test" style="font-size:20px;">abc</div>