Javascript为firefox实现innerText属性

0、为什么要innerText?因为安全问题
1、为firefox dom模型扩展属性 
2、currentStyle属性可以取得实际的style状态
3、IE实现innerText时考虑了display方式,如果是block则加换行
4、为什么不用textContent?因为textContent没有考虑元素的display方式,所以不完全与IE兼容
 

XML/HTML代码
  1. <html>  
  2. <body>  
  3. <div id="d1"><a href="aa">ccc</a>ddd<div>eeee</div>fff</div>  
  4. <script type="text/javascript">  
  5. <!--   
  6. //   
  7. // patch of innerText for firefox   
  8. //   
  9. (function (bool) {   
  10.     function setInnerText(o, s) {   
  11.         while (o.childNodes.length != 0) {   
  12.             o.removeChild(o.childNodes[0]);   
  13.         }   
  14.   
  15.         o.appendChild(document.createTextNode(s));   
  16.     }   
  17.   
  18.     function getInnerText(o) {   
  19.         var sRet = "";   
  20.   
  21.         for (var i = 0; i < o.childNodes.length; i ++) {   
  22.             if (o.childNodes[i].childNodes.length != 0) {   
  23.                 sRet += getInnerText(o.childNodes[i]);   
  24.             }   
  25.   
  26.             if (o.childNodes[i].nodeValue) {   
  27.                 if (o.currentStyle.display == "block") {   
  28.                     sRet += o.childNodes[i].nodeValue + "\n";   
  29.                 } else {   
  30.                     sRet += o.childNodes[i].nodeValue;   
  31.                 }   
  32.             }   
  33.         }   
  34.   
  35.         return sRet;   
  36.     }   
  37.   
  38.     if (bool) {   
  39.         HTMLElement.prototype.__defineGetter__("currentStyle", function () {   
  40.             return this.ownerDocument.defaultView.getComputedStyle(this, null);   
  41.         });   
  42.   
  43.         HTMLElement.prototype.__defineGetter__("innerText", function () {   
  44.             return getInnerText(this);   
  45.         })   
  46.   
  47.         HTMLElement.prototype.__defineSetter__("innerText", function(s) {   
  48.             setInnerText(this, s);   
  49.         })   
  50.     }   
  51. })(/Firefox/.test(window.navigator.userAgent));   
  52. //-->  
  53. </script>  
  54.   
  55. <script type="text/javascript">  
  56. <!--   
  57. var d1 = document.getElementById("d1");   
  58.   
  59. alert(d1.innerText);   
  60. d1.innerText = "xxx";   
  61. //-->  
  62. </script>  
  63. </body>  
  64. </html>  


上一篇: 经常会用到的Javascript检测函数
下一篇: Javascript兼容 IE Firefox 的键盘控制事件
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: javascript
相关日志:
评论: 0 | 引用: 0 | 查看次数: 1778
发表评论
昵 称:
密 码: 游客发言不需要密码.
邮 箱: 邮件地址支持Gravatar头像,邮箱地址不会公开.
网 址: 输入网址便于回访.
内 容:
验证码:
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 开启 | [img]标签 关闭

 广告位

↑返回顶部↑