參考:https://www.softwhy.com/HTML5/MutationObserver_course/
JavaScript監聽屬性改變
原創作品,轉載需得到原作者書面許可,同時保留原作者和出處,否則將追究法律責任。
關於Mutation Observer基本知識可以參閱以下兩篇文章:
(1).Mutation Observer優點一章節。
(2).Mutation Observer用法一章節。
下面通過代碼實例介紹一下如何監聽attributes的變動,也就是監聽子節點的變動。
代碼實例如下:
[HTML]
純文本查看 復制代碼
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
<!doctype html>
<
html
>
<
head
>
<
meta
charset
=
"utf-8"
>
<
title
>螞蟻部落</
title
>
<
script
>
window.onload = function () {
var ul = document.querySelector("ul");
var Observer = new MutationObserver(function (mutations, instance) {
console.log(mutations);
console.log(instance);
mutations.forEach(function (mutation) {
console.log(mutation);
});
});
Observer.observe(ul, {
attributes: true
});
ul.setAttribute("class", "a");
ul.setAttribute("class", "b");
ul.removeAttribute("class");
}
</
script
>
</
head
>
<
body
>
<
div
id
=
"box"
>
<
ul
>
<
li
>螞蟻部落</
li
>
</
ul
>
</
div
>
</
body
>
</
html
>
|
下面對代碼進行一下分析,首先看運行控制台截圖:
![aid[1351] a:3:{s:3:\"pic\";s:43:\"portal/201808/18/013616uv3s3vvev3x3fxs3.png\";s:5:\"thumb\";s:0:\"\";s:6:\"remote\";N;}](/image/aHR0cHM6Ly93d3cuc29mdHdoeS5jb20vZGF0YS9hdHRhY2htZW50L3BvcnRhbC8yMDE4MDgvMTgvMDEzNjE2dXYzczN2dmV2M3gzZnhzMy5wbmc=.png)
當其他所有腳本代碼都執行完畢之后,MutationObserver構造函數的回調函數才會被執行。
構造函數的第一個數組參數用來存放所有的變化,每一個成員都是MutationRecord類型。
[JavaScript]
純文本查看 復制代碼
|
1
2
3
|
Observer.observe(ul, {
attributes:
true
//監聽屬性節點的變化
});
|
規定監聽器將監聽ul元素屬性節點的變化。
[JavaScript]
純文本查看 復制代碼
|
1
|
ul.setAttribute(
"class"
,
"a"
)
|
為ul元素添加一個class屬性,並設置屬性值為a;動作將被記錄在mutations數組中。
[JavaScript]
純文本查看 復制代碼
|
1
|
ul.setAttribute(
"class"
,
"b"
)
|
修改ul元素原來class屬性值為b;動作將被記錄在mutations數組中。
[JavaScript]
純文本查看 復制代碼
|
1
|
ul.removeAttribute(
"class"
);
|
刪除ul元素上的class屬性;動作將被記錄在mutations數組中。
MutationRecord對象,直接看控制台截圖:
![aid[1352] a:3:{s:3:\"pic\";s:43:\"portal/201808/18/013625ig6w7gljo0lz7p8h.png\";s:5:\"thumb\";s:0:\"\";s:6:\"remote\";N;}](/image/aHR0cHM6Ly93d3cuc29mdHdoeS5jb20vZGF0YS9hdHRhY2htZW50L3BvcnRhbC8yMDE4MDgvMTgvMDEzNjI1aWc2dzdnbGpvMGx6N3A4aC5wbmc=.png)
監聽指定屬性的改變:
如果不指定監聽哪些屬性,那么所有屬性的改變都在監聽范圍之內。
Mutation Observer提供了監聽指定屬性的功能,代碼實例如下:
[HTML]
純文本查看 復制代碼
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
<!doctype html>
<
html
>
<
head
>
<
meta
charset
=
"utf-8"
>
<
title
>螞蟻部落</
title
>
<
script
>
window.onload = function () {
var ul = document.querySelector("ul");
var Observer = new MutationObserver(function (mutations, instance) {
console.log(mutations);
console.log(instance);
mutations.forEach(function (mutation) {
console.log(mutation);
});
});
Observer.observe(ul, {
attributes: true,
attributeFilter: ["class"]
});
ul.setAttribute("class", "a");
ul.setAttribute("ant", "b");
}
</
script
>
</
head
>
<
body
>
<
div
id
=
"box"
>
<
ul
>
<
li
>螞蟻部落</
li
>
</
ul
>
</
div
>
</
body
>
</
html
>
|
上面代碼只會監聽class屬性的變化。
attributeFilter屬性值是一個數組,可以規定要監聽的屬性名稱。
