当前位置:网站首页>Detailed explanation of mutationobserver
Detailed explanation of mutationobserver
2022-06-11 06:56:00 【Xiaoman's code world】
MutationObserver Used to monitor DOM change .DOM Any changes , Let's say I add or subtract nodes 、 Change of attribute 、 Any change in the text content will trigger MutationObserver event .
however , It has an essential difference from events : Events are triggered synchronously , in other words ,DOM Immediately triggers the corresponding event ;Mutation Observer It is triggered asynchronously ,DOM The change will not be triggered immediately , Instead, wait until it's all there DOM This is triggered after all operations are completed .
Mutation Observer Has the following characteristics :
- It waits for all the script tasks to complete , Will run ( Asynchronous trigger mode ).
- It is the DOM The change records are encapsulated in an array for processing , Not one by one DOM change .
- It can both observe DOM All types of changes , You can also specify that only one type of change be observed .
MutationObserver Constructors
var observer = new MutationObserver(function (mutationRecoards, observer) {
// mutationRecoards Variable array
// observer Observer example
});
The constructor receives a callback function , The callback function takes two arguments , A variable array , The second is the observer instance .
MutationObserver Instance method of
1. observe(node, config)
Start listening , It takes two arguments .
The first parameter : To observe DOM node
The second parameter : A configuration object , Specify the specific changes to be observed
The configuration objects are as follows :
- childList: Changes in child nodes ( Refers to new , Delete or change ).
- attributes: Change of attribute .
- characterData: Changes in node content or node text .
- subtree: Boolean value , Indicates whether the observer is applied to all descendant nodes of the node .
- attributeOldValue: Boolean value , To observe attributes When changing , Whether it is necessary to record the attribute value before the change .
- characterDataOldValue: Boolean value , To observe characterData When changing , Is it necessary to record the value before the change .
- attributeFilter: Array , Represents a specific attribute that needs to be observed ( such as [‘class’,‘src’]).
// Start listening to the document root node ( namely <html> label ) The change of
mutationObserver.observe(document.documentElement, {
attributes: true,
characterData: true,
childList: true,
subtree: true,
attributeOldValue: true,
characterDataOldValue: true
});
Add an observer to a node , It's like using addEventListener The method is the same , Adding the same observer more than once is invalid , The callback function will still trigger only once . however , If you specify a different options object , Will be treated as two different observers .
2. disconnect()
disconnect Method to stop observation . After calling this method ,DOM Another change , And it doesn't trigger the viewer .
3. takeRecords()
Used to clear change records , That is, it no longer deals with unprocessed changes . This method returns an array of change records .
MutationRecord object
DOM Every time it changes , A change record will be generated (MutationRecord example ). This example contains all the information about the change .Mutation Observer What we deal with is one by one MutationRecord The array of instances .
MutationRecord The object contains DOM Information about , Has the following properties :
- type: Types of changes observed (attribute、characterData perhaps childList).
- target: fluctuating DOM node .
- addedNodes: Newly added DOM node .
- removedNodes: Delete the DOM node .
- previousSibling: The previous sibling node , If not, return null.
- nextSibling: Next sibling node , If not, return null.
- attributeName: A property that has changed . If set attributeFilter, Returns only the previously specified properties .
- oldValue: The value before the change . This property is only true attribute and characterData Changes in the effective , In case of childList change , Then return to null.
Example
<div id="container">
<div class="child"></div>
</div>
<button id="update">
change
</button>
<script>
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver
const container = document.getElementById('container')
const button = document.getElementById('update')
const options = {
attributes: true,
childList: true,
}
// establish MutationObserver example , Returns an observer object
const mutation = new MutationObserver(function(mutationRecoards, observer) {
console.log(mutationRecoards)
console.log(observer)
})
// Add elements to the observer that need to be observed , And set which aspects of the element you want to observe
mutation.observe(container, options);
// Yes container To operate
button.addEventListener('click', function() {
container.innerText = ' This is the text '; // Content change
container.style.background = 'red'; // Property change
for (let i = 0; i < 3; i++) { // Child node
container.appendChild(document.createElement('div'))
}
})
</script>

Reference resources
边栏推荐
- [turn] flying clouds_ Qt development experience
- Flutter 内外边距
- Xunwei dry goods | Ruixin micro rk3568 development board TFTP & NFS writing (Part 1)
- 双周投融报:资本抢滩元宇宙游戏
- Luogu p1091 chorus formation (longest ascending subsequence)
- 关于组织开展2022年宁波市重点首版次软件申报工作的通知
- 022 basic introduction to redis database 0
- 河南高考VS天津高考(2008年-2021年)
- Post exam summary
- Handwritten a message queue in two ways
猜你喜欢
![Resolve typeerror: ctx injections. tableRoot.$ scopedSlots[ctx.props.column.slot] is not a function](/img/29/de95cef86bd75107555b212f01ebb9.jpg)
Resolve typeerror: ctx injections. tableRoot.$ scopedSlots[ctx.props.column.slot] is not a function

河南高考VS天津高考(2008年-2021年)

. Net C Foundation (6): namespace - scope with name

The nearest common ancestor of 235 binary search tree

Stack -- one of two common linear structures of linear structure
![Handwritten promise [05] - exception capture of promise method and optional parameters of then method implementation](/img/e7/87069f921ae003511e32b23653703c.jpg)
Handwritten promise [05] - exception capture of promise method and optional parameters of then method implementation

Sohu employees encounter wage subsidy fraud. What is the difference between black property and gray property and how to trace the source?

Esp32 learning notes (49) - esp-wifi-mesh interface use

Simple integration of client go gin six list watch two (about the improvement of RS, pod and deployment)

关于 QtCreator的设计器QtDesigner完全无法正常拽托控件 的解决方法
随机推荐
22年五月毕设
The nearest common ancestor of 235 binary search tree
About the designer of qtcreator the solution to the problem that qtdesigner can't pull and hold controls normally
Flutter Container组件
How to make time planning
Luogu p1091 chorus formation (longest ascending subsequence)
About daily report plan
Flutter 约束容器组件
Handwritten promise [05] - exception capture of promise method and optional parameters of then method implementation
Flutter 内外边距
client-go gin的简单整合六-list-watch二(关于Rs与Pod以及Deployment的完善)
ESP32学习笔记(49)——ESP-WIFI-MESH接口使用
021 mongodb database from getting started to giving up
Summary of string processing skills II
Oracle prompt invalid number
Comparison of DOM tags of wechat applet development (native and uniapp)
Saltstack deployment LNMP
[matlab WSN communication] a_ Star improved leach multi hop transmission protocol [including source code phase 487]
VTK-vtkPlane和vtkCutter使用
Use of qscriptengine class