【问题标题】:Detecting class change without setInterval在没有 setInterval 的情况下检测类变化
【发布时间】:2017-06-26 13:39:49
【问题描述】:

我有一个div,它以编程方式添加了其他类。如何在不使用 setInterval 实现的情况下检测类名更改?

setInterval(function() {
    var elem = document.getElementsByClassName('original')[0];
    if (elem.classList.contains("added")) { detected(); }
}, 5500);

突变观察者?

【问题讨论】:

标签: javascript html setinterval mutation-observers


【解决方案1】:

您可以使用mutation observer。现在很widely supported

var e = document.getElementById('test')
var observer = new MutationObserver(function (event) {
  console.log(event)   
})

observer.observe(e, {
  attributes: true, 
  attributeFilter: ['class'],
  childList: false, 
  characterData: false
})

setTimeout(function () {
  e.className = 'hello'
}, 1000)
<div id="test">
</div>

【讨论】:

    猜你喜欢
    • 2021-10-06
    • 2015-02-23
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多