簡體   English   中英

檢測JS中CSSStyleDeclaration對象的更改

[英]Detect changes of CSSStyleDeclaration object in JS

CSSStyleDeclaration對象發生更改時,是否有任何方式可以得到通知,就像可以使用DomAttrModified這樣的事件來跟蹤DOM更改一樣?

因此,例如,如果有一些JS代碼,例如

document.styleSheets[0].rules[0].style.backgroundImage = "url(myimage.png)";

有沒有辦法在不更改上面的代碼片段的情況下獲得有關JS處理程序中的更改的通知?

提前致謝!

我認為沒有本地可用的功能。

根據您的用例,您可以輕松地構建包裝器,以便您的代碼使用該包裝器並通知偵聽器某些更改。

像這樣的基本東西:

function Wrapper() {
    var listeners = []

    return {
        addListener: function(fn) {
            listeners.push(fn)
        },
        removeListener: function(fn) {
            listeners.splice(listeners.indexOf(fn), 1) // indexOf needs shim in IE<9
        },
        set: function(prop, val) {
            prop = val
            // forEach needs shim in IE<9, or you could use a plain "for" loop
            listeners.forEach(call)

            function call(fn) {
                fn(prop, val)
            })
        }
    }
}

您可以這樣使用:

var wrapper = Wrapper()
wrapper.addListener(function(prop, val) {
    // When you'll change a prop, it'll get there and you'll see
    // which property is changed to which value
})

// This sets the property and notifies all the listeners
wrapper.set(document.styleSheets[0].rules[0].style.backgroundImage, "url(myimage.png)")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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