我的 div 看起来像这样:
<div tabindex="0" role="button" id="profile-pic" style="background-image: "Some url";"></div>
背景图像将根据某些标准进行更新。我想将监听器设置为样式属性并监听背景图像更改。可能吗?
最佳答案
您可以使用MutationObserver
然后是代码示例:
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutationRecord) {
console.log('style changed!');
});
});
var target = document.getElementById('myId');
observer.observe(target, {
attributes: true,
attributeFilter: ['style']
});
注意:这仅适用于内联样式(任何样式更改),不适用于因类更改或 @media 更改而导致样式更改的情况 这是一个答案https://stackoverflow.com/a/20683311/3344953
关于javascript - 在 Javascript 中设置样式更改事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55590763/