很多程式碼寫了又忘、忘了又寫,容易造成浪費,因此決定養成做筆記的習慣。本文記錄如何在 Firefox 中模擬 innerText。
知識點:
0、為何要 innerText?主要是基於安全考量。
1、為 Firefox 的 DOM 模型擴充屬性。
2、currentStyle 屬性可取得實際的 style 狀態。
3、IE 實作 innerText 時考慮了 display 方式,若為 block 則加換行。
4、為何不用 textContent?因為它沒有考慮元素的 display 方式,不完全與 IE 相容。
<html>
<body>
<div id="d1"><a href="aa">ccc</a>ddd<div>eeee</div>fff</div>
<script type="text/javascript">
<!--
//
// patch of innerText for firefox
//
(function (bool) {
function setInnerText(o, s) {
while (o.childNodes.length != 0) {
o.removeChild(o.childNodes[0]);
}
o.appendChild(document.createTextNode(s));
}
function getInnerText(o) {
var sRet = "";
for (var i = 0; i < o.childNodes.length; i ++) {
if (o.childNodes[i].childNodes.length != 0) {
sRet += getInnerText(o.childNodes[i]);
}
if (o.childNodes[i].nodeValue) {
if (o.currentStyle.display == "block") {
sRet += o.childNodes[i].nodeValue + "\n";
} else {
sRet += o.childNodes[i].nodeValue;
}
}
}
return sRet;
}
if (bool) {
HTMLElement.prototype.__defineGetter__("currentStyle", function () {
return this.ownerDocument.defaultView.getComputedStyle(this, null);
});
HTMLElement.prototype.__defineGetter__("innerText", function () {
return getInnerText(this);
})
HTMLElement.prototype.__defineSetter__("innerText", function(s) {
setInnerText(this, s);
})
}
})(/Firefox/.test(window.navigator.userAgent));
-->
</script>
<script type="text/javascript">
<!--
var d1 = document.getElementById("d1");
alert(d1.innerText);
d1.innerText = "xxx";
-->
</script>
</body>
</html>