使用Jquery监视属性更改

时间:2015-11-09 15:38:34

标签: javascript jquery

我需要在div的属性发生变化时触发事件。我遇到了这个插件http://meetselva.github.io/attrchange/,似乎可以解决这个问题。唯一的问题是它多次触发事件。例如,如果我这样做:

$("#sgPluginBox").attrchange({

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

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

编辑:

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

1 个答案:

答案 0 :(得分:0)

尝试使用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>
&#13;
&#13;
&#13;