如何在更改dom元素样式后调用函数Javascript / jquery

我已经经历了多个示例,并实现了与示例所述相同的行为。

加载页面后,如果dom元素的样式发生变化,我需要触发一个方法。

即使我在浏览器控制台中更改了任何内容,也应该触发样式更改事件。 该事件将显示无和显示块。

在我的代码中,如果在浏览器控制台中进行更改,则不会触发更改方法。

这是我试过的:

(function() { var ev = new $.Event('style'), orig = $.fn.css; $.fn.css = function() { var ret = orig.apply(this, arguments); $(this).trigger(ev); return ret; } })(); $('p').bind('style', function(e) { console.log($(this).attr('style')); }); 
 p { display: none; } 
  

test

你可以使用MutationObserver :

演示:

 // create an observer instance var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { var oldDisplay = (mutation.oldValue + '').match(/display:\s*(\w*)/); oldDisplay = oldDisplay ? oldDisplay[1] : ''; if (oldDisplay !== mutation.target.style.display) { console.log('element', mutation.target.id, 'style.display=', mutation.target.style.display); } }); }); // attach the observer to the elements of interest: $('p').each(function () { observer.observe(this, { attributes: true, attributeFilter: ['style'], attributeOldValue: true }); }); // test it, by changing style.display through button clicks: $('button').click(function() { $('p').toggle(); // show/hide }); 
  

test this