5

假设我有以下 HTML:

<div id='content'></div>

当此元素发生高度突变时,我希望收到警报。我希望MutationObserver类对此有所帮助,但这是我的问题:

document.querySelector('#content').style.height = '100px'

它像预期的那样触发我的回调,但是正常的用户交互不会触发这个,例如, http: //jsfiddle.net/wq4q9/2/

我的问题是,检查元素高度是否发生变化的最佳现代方法是什么?

请不要使用 jQuery。

4

2 回答 2

1

You'll probably have to go along with T.J. Crowders recommendation to poll, however your code example isn't working for other reasons (it seems):

The documentation* for childList says that it is used to monitor additions and removals of the target node's child elements.

* This is the first and only time I'll reference MSDN as opposed to MDN, because the MDN documentation for this is crap.


The record you should be observing is subtree:

Set to true to also monitor changes to all the target node's descendants


If you do that, then the code works in Firefox.

var target = document.querySelector('#content');

var observer = new MutationObserver(function(mutations) {
  console.log(mutations);   
});

var config = { attributes: true, childList: true, subtree: true, characterData: true };
observer.observe(target, config);

document.querySelector('button').addEventListener('click',function(){
    target.style.height = '200px';
});

However, it still doesn't work in Chrome; likely because of the Chrome bug reported in this question.

于 2014-06-01T17:53:19.903 回答
1

我认为除了民意调查之外你无能为力。(另一种不会触发您的观察者的方法是,如果您更改了应用于元素的 CSS 规则,更改了其父级的大小并且其大小取决于该元素,添加了一个影响它的新样式表......)

于 2014-06-01T17:26:34.377 回答