簡體   English   中英

在Javascript中設置樣式更改事件監聽器

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM