让FireFox支持innerText的实现代码 |
为firefox实现innerText属性 很多代码写了又忘忘了又写,很浪费,所以决定养成做笔记的习惯 。 知识点: 0、为什么要innerText?因为安全问题 1、为firefox dom模型扩展属性 2、currentStyle属性可以取得实际的style状态 3、IE实现innerText时考虑了display方式,如果是block则加换行 4、为什么不用textContent?因为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> 今天在制作firefox下支持复制的js代码的时候,用到了innerText,测试发现原来firefox支持innerHTML但不支持innerText,所以上网找了一下,发现了一篇非常不错的代码 。另从回复中,我们得到了如下兼容代码 。修正了原来ie下出现错误提示的问题 。具体的看下么的文章 。 把这段加在你所JS文件中就可以在MOZILLA/FIREFOX下使用innerText 复制代码 代码如下: HTMLElement.prototype.__defineGetter__ ( "innerText", function () { var anyString = ""; var childS = this.childNodes; for(var i=0; i<childS.length; i++) { if(childS[i].nodeType==1) anyString += childS[i].tagName=="BR" ? \n : childS[i].innerText; else if(childS[i].nodeType==3) anyString += childS[i].nodeValue; } return anyString; } ); 但这段代码在IE中它会提示HTMLElement未定义,下面就是具体的解决方法 。 复制代码 代码如下: function isIE(){ //ie? 判断是不是ie if (window.navigator.userAgent.indexOf("MSIE")>=1) return true; else return false; } if(!isIE()){ HTMLElement.prototype.__defineGetter__ ( "innerText", function () { var anyString = ""; var childS = this.childNodes; for(var i=0; i<childS.length; i++) { if(childS[i].nodeType==1) anyString += childS[i].tagName=="BR" ? \n : childS[i].innerText; else if(childS[i].nodeType==3) anyString += childS[i].nodeValue; } return anyString; } ); } |