显示新通知的最佳方式

Best way to show new notifications

本文关键字:最佳 方式 通知 新通知 显示      更新时间:2023-09-26

我正在开发一个系统,其中有一个带有图标的通知部分,如果有新的通知到达,我必须高亮该图标。我想使用的第一个解决方案是DOMNodeInserted到通知窗格的容器div。但是这种方法已经被弃用了。第二个选项是实现一个计时器,它检查dom计数是否增加,并根据该计时器突出显示图标。

是否有更好的方法来实现这个场景使用JavaScript。

该事件已被弃用,取而代之的是所有现代浏览器都支持的突变观察者。https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

// select the target node
var target = document.querySelector('#some-id');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });    
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);
// later, you can stop observing
observer.disconnect();