MutationObserver
MutationObserver Attributes行為觀察
by sj82516
HTML
<ul id="observer-list">
<li class="oberserver-list__item">hello</li>
<li class="oberserver-list__item">mutation oberser</li>
</ul>
CSS
.highlight{
color: red;
}
JavaScript
/*
creator : YJ Cheng
*/
const target = document.querySelector('#observer-list');
let observer1 = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(
"屬性:",mutation.type,
"改變屬性名稱:",mutation.attributeName,
"舊的屬性值:",mutation.oldValue);
});
});
// 一秒觀察一種行為,先看改變屬性
setTimeout(()=>{
observer1.observe(target, {
attributes: true,
attributeOldValue: true
});
target.setAttribute("class", "highlight")
}, 1000)
// 加入attributeOldValue才會紀錄oldValue,註解掉oldValue永遠是null
setTimeout(()=>{
observer1.observe(target, {
attributes: true,
attributeOldValue: true
});
target.setAttribute("class", "highlight2")
}, 2000)
// 加入attributeFilter僅觀察style,如果註解掉會多出現一行 class
setTimeout(()=>{
observer1.observe(target, {
attributes: true,
attributeOldValue: true,
attributeFilter: ['style']
});
target.setAttribute("class", "highlight3")
target.setAttribute("style", "color:blue")
}, 3000)