检测JS中CSSStyleDeclaration对象的变化

muf*_*fel 8 html javascript css dom

有什么方法可以在CSSStyleDeclaration对象发生更改时得到通知,就像DOM更改一样,可以使用像DomAttrModified这样的事件进行跟踪?

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

document.styleSheets[0].rules[0].style.backgroundImage = "url(myimage.png)";
Run Code Online (Sandbox Code Playgroud)

有没有办法在不改变上面的代码片段的情况下在JS处理程序中获得有关该更改的通知?

提前致谢!

Flo*_*ine 1

我认为没有任何本地可用的东西。

根据您的用例,您可以轻松构建一个包装器,以便您的代码使用该包装器并通知侦听器某些内容发生了更改。

像这样的非常基本的东西:

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)
            })
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以这样使用:

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)")
Run Code Online (Sandbox Code Playgroud)