js 監聽html 元素的變化

<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="Generator" content="EditPlus®">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>Document</title>
 </head>
 <body>
    <div id="root">aaaaa</div>	
 </body>
</html>
<script>
	// 監聽對象屬性的變換.
	var  targetNode= document.getElementById("root");
	console.log(targetNode);
	
	//需要監聽的屬性.
	// 節點本身屬性的檢查, 子節點列表, 子樹的變換.
	var config={attributes:true,childList:true,subtree:true};

	// 使用定時器修改對象的屬性, 
	var callback = function(mutationsList,observer){
		//console.log(mutationsList);
		//console.log(observer);
		for(var mutation of mutationsList)
		{
			if (mutation.type=='childList')
			{
				console.log("this is childlist change");
			}else if(mutation.type=='attributes')
			{
				console.log("this  is attributes");
			}else{
				console.log("this is subtree");
			}
		}
	};
	
	var observer  =  new MutationObserver(callback);
	observer.observe(targetNode,config);

	// 清楚要監聽的內容. 
	// setTimeout和setInterval
	// 爲了測試自動化.
	setTimeout(function(){
		console.log(targetNode);
		targetNode.setAttribute("style","color:red;");
		
	},2000);
	
	// 這個不可以在屬性修改前,否則沒有效果, 
    //observer.disconnect();

</script>

具體的函數定義, 主要是observe的第二個參數的說明.

https://dom.spec.whatwg.org/#mutationobserver  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章