1. 程式人生 > >低版本Firefox支援innerText屬性相容方法

低版本Firefox支援innerText屬性相容方法


FireFox支援innerText屬性了,很遺憾是44.0.2版還需要相容處理

innerHTML是符合W3C標準的屬性,而innerText只適用於IE瀏覽器,因此,儘可能地去使用innerHTML,而少用innerText,如果要輸出不含HTML標籤的內容,可以使用innerHTML取得包含HTML標籤的內容後,再用正則表示式去除HTML標籤或者用innerText更便捷。

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>innerText</title>
</head>
<body>
<div id="hello">this is a paragraph <p>hello world</p></div>
	<script>

		if(!('innerText' in document.body)){ /* 一個不是w3c標準的屬性 能展現節點及子節點的文字 FireFox 45以下版本不支援, 45及之後的版本都支援了*/
			HTMLElement.prototype.__defineGetter__("innerText", function(){
				return this.textContent;
			});
			HTMLElement.prototype.__defineSetter__("innerText", function(s){
				return this.textContent = s;
			});
		}
   		var p = document.getElementById('hello');
   		console.log(p.innerText);

   		p.innerText = "the paragraph has changed!";
   		console.log(p.innerText);

	</script>
</body>
</html>


FireFox輸出: this is a paragraph hello world the paragraph has changed! Chrome輸出: this is a paragraph
hello world
the paragraph has changed!