Mutation Obeserver不会触发动态变化的回调

时间:2015-09-14 13:38:11

标签: javascript jquery css mutation-observers

我已经定义了两个<div>个元素,一个在另一个内部。我听内容<div>width:auto;。当我更改父<div>的宽度时,我预期来自变异观察者的回调会触发,因为目标<div>的宽度会发生变化。但它没有发生。

出了什么问题?

&#13;
&#13;
// Blocker is the element that has a changing display value
var blocker = document.querySelector('#blocker');
// Trigger changes the display value of blocker
var trigger = document.querySelector('#trigger');
// Our mutation observer, which we attach to blocker later
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    // Was it the style attribute that changed? (Maybe a classname or other attribute change could do this too? You might want to remove the attribute condition) Is display set to 'none'?
    if (mutation.attributeName === 'style') {
      alert(window.getComputedStyle(blocker).getPropertyValue('width'));
    }
  });
});

// Attach the mutation observer to blocker, and only when attribute values change
observer.observe(blocker, {
  attributes: true
});

// Make trigger change the style attribute of blocker
trigger.addEventListener('click', function() {
  $('#d').css('width', '300px');
  //     $('#blocker').css('background-color','red'); 
}, false);
&#13;
#d {
  width: 200px;
}
#blocker {
  width: auto;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="d">
  <div id="blocker" style="display:none">Stop!</div>
</div>
<div id="trigger">Show blocking element</div>
&#13;
&#13;
&#13;

View on JSFiddle

1 个答案:

答案 0 :(得分:0)

您正在观察#blocker div的孩子#d div。但点击即可更改父属性(#d)。 MutationObserver只能观察元素本身或元素和子树(MDN)。因此,不会触发回调,因为您只是简单地更改了另一个DOM元素的属性