Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
Mutation Observer 是一个内置对象,提供了一种观察 DOM 变化并对其做出反应的方法。它是构建需要实时 DOM 操作和事件处理的动态网络应用程序的强大工具。通过 Mutation Observer,您可以监控文档中特定节点、属性或子元素的变化,并执行自定义函数来响应这些变化。
在 Aspose.HTML for Java 库中,
MutationObserver 类代表了一种文档观察机制,该类易于配置,可以接收文档树中任何变化的通知。本文使用 Java 示例来说明如何使用 MutationObserver 类来观察 DOM 中的变化。
Mutation Observer 提供了观察网页 DOM 树变化的功能。下面的示例演示了 MutationObserver 的实现,以及如何使用它来观察向文档中添加新节点的情况。
ChildList、Subtree 和 CharacterData 属性设置为 true。<body> 元素或其子节点发生符合配置选项的变化时,将调用回调函数来处理这些变化。<p> 元素,并使用
appendChild() 方法将其添加到文档的正文中;使用
createTextNode() 方法创建一个内容为 “Hello, World!“的文本节点,并使用 appendChild() 方法将其添加为<p>元素的子节点。 1// Monitor DOM tree changes using MutationObserver API in Aspose.HTML for Java
2
3// Create an empty HTML document
4HTMLDocument document = new HTMLDocument();
5
6// Create an instance of the MutationObserver class
7MutationObserver observer = new MutationObserver(new MutationCallback() {
8
9 @Override
10 public void invoke(com.aspose.html.utils.collections.generic.IGenericList<MutationRecord> mutations, MutationObserver mutationObserver) {
11 for (int i = 0; i < mutations.size(); i++) {
12 MutationRecord record = mutations.get_Item(i);
13 for (Node node : record.getAddedNodes().toArray()) {
14 System.out.println("The '" + node + "' node was added to the document.");
15 }
16 }
17 }
18});
19
20// Configure options for the MutationObserver
21MutationObserverInit config = new MutationObserverInit();
22config.setChildList(true);
23config.setSubtree(true);
24config.setCharacterData(true);
25
26// Pass to observer the target node to observe with the specified configuration
27observer.observe(document.getBody(), config);
28
29// Now, we are going to modify DOM tree to check
30// Create a paragraph element and append it to the document body
31Element p = document.createElement("p");
32document.getBody().appendChild(p);
33
34// Create a text and append it to the paragraph
35Text text = document.createTextNode("Hello, World!");
36p.appendChild(text);
37
38System.out.println("Waiting for mutation. Press any key to continue...");
39System.in.read();MutationObserver 时,选择特定目标并关注特定元素或属性,以优化性能并减少不必要的处理。MutationObserverInit 对象对观测参数进行微调。只包含必要的属性(如 ChildList、Subtree、CharacterData),以优化流程。如果您正在观察节点的变化,那么在 DOM 完全完成变化之前,您的回调将不会被触发。设计这种行为是为了取代 DOM 突变事件,减少以前规范中的杀毒性能问题。
您可以从 GitHub 下载完整的示例和数据文件。
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.