我想同步一些DOM节点属性。如果某个属性发生更改,则会更改其他元素属性。
在里面
this example
#div1
给另外两个人。
html:
<div id="div1" class="foo"></div>
<div id="div2" class="foo"></div>
<div id="div3" class="foo"></div>
js:
let div1 = document.getElementById("div1")
let div2 = document.getElementById("div2")
let div3 = document.getElementById("div3")
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.target.getAttribute("class"))
//sync the new attribute value to
div2.setAttribute("class", mutation.target.getAttribute("class"))
div3.setAttribute("class", mutation.target.getAttribute("class"))
})
})
// pass in the target node, as well as the observer options
observer.observe(div1, { attributes: true, attributeFilter: ["class"]})
//the test sets the class attribute of div1 to 'bar'
div1.setAttribute("class", "bar")
//then checks if div2 and div3 class is set to 'bar'
console.log("is div2.class = 'bar'?", div2.getAttribute("class") == "bar")
console.log("is div3.class = 'bar'?", div3.getAttribute("class") == "bar")
is div2.class = 'bar'? false
is div3.class = 'bar'? false
bar
MutationObserver
仅在检查后运行,然后
div2.class
和
div3.class
设置为
'bar'