[英]Set style change event listener in Javascript
我的div看起来像这样:
<div tabindex="0" role="button" id="profile-pic" style="background-image: "Some url";"></div>
背景图像将根据一些标准进行更新。 我想将侦听器设置为样式属性,并侦听背景图像更改。 可能吗?
MutationObserver是可能的 ,但这样做有点奇怪:
console.log('Script start'); const div = document.querySelector('div'); const o = new MutationObserver(() => { console.log('style changed'); }); o.observe(div, { attributes: true, attributeFilter: ["style"] }); setTimeout(() => { div.style.backgroundImage = 'url(https://www.gravatar.com/avatar/34932d3e923ffad9a4a1423e30b1d9fc?s=48&d=identicon&r=PG&f=1)'; }, 500);
<div tabindex="0" role="button" id="profile-pic" style="background-image: 'Some url';">xx</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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.