如何调用函数一旦dom元素的样式改变Javascript/jquery

How to invoke function once the dom element style is changed Javascript/jquery

本文关键字:样式 元素 改变 Javascript jquery dom 何调用 调用 函数      更新时间:2023-09-26

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

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

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

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

这是我尝试过的:

(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;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p> test </p>

您可以使用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
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="p1"> test this </p><button>hide/show</button>