HTML 检测元素样式的变化

Flo*_*ain 1 html javascript

我想知道是否有办法检测嵌入到 html 中的某些样式是否已更改,例如:

<div id="corps" style="display: block;">
Run Code Online (Sandbox Code Playgroud)

是否有一个事件可以检测“显示”何时发生变化?(Javascript,而不是 Jquery 或其他东西)WC 文档对事件检测到的内容不是很清楚(例如“onchange”)

gae*_*noM 5

您可以使用MutationObserver:

document.querySelector('button').addEventListener('click', function(e) {
    var ele = document.getElementById('corps');
    if (ele.style.display == 'block')
        ele.style.display = 'none';
    else
        ele.style.display = 'block';
});


var observer = new MutationObserver(function(mutationsList, observer) {
    for (var mutation of mutationsList){
        console.log('The ' + mutation.attributeName + ' attribute was modified.');
    }
});
observer.observe(document.getElementById('corps'), { attributes: true});
Run Code Online (Sandbox Code Playgroud)
<div id="corps" style="display: block;">1111111111111111</div>
<button>Change div style</button>
Run Code Online (Sandbox Code Playgroud)