Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 117 期(JavaScript-DOM):监听页面DOM元素的插入 #120

Open
wingmeng opened this issue Sep 27, 2019 · 0 comments
Open

第 117 期(JavaScript-DOM):监听页面DOM元素的插入 #120

wingmeng opened this issue Sep 27, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

监听页面中 DOM 节点的插入是一个很实用的功能,例如我们可以在节点插入到页面之前对其进行初始化。

document.addEventListener('DOMNodeInserted', function(event) {
  console.log(event.target.nodeName.toLowerCase())
  console.log('type', event.type);        // 1:DOMNodeInserted
  console.log('element', event.target);      // 2:被添加的节点
  console.log('relate', event.relatedNode); // 3:被添加节点的父节点
});

需要注意的是 DOMNodeInserted 这类 mutation 事件在标准中已不赞成使用,推荐用 Mutation Observers 代替。

var observer = new MutationObserver(function(mutationsList) {
  mutationList.forEach(function(mutation) {
    switch(mutation.type) {
      case 'childList':
        /* 从树上添加或移除一个或更多的子节点 */

        break;
      case 'attributes':
        /* mutation.target 中某节点的一个属性值被更改 */
        break;
    }
  });
});

observer.observe(document.body, {
  childList:  true,  // 观察目标子节点的变化,添加或者删除
  attributes: true,  // 观察属性变动
  subtree:    true   // 默认为 false,设置为 true 可以观察后代节点
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant