Heim  >  Artikel  >  Web-Frontend  >  让FireFox支持innerText的实现代码_javascript技巧

让FireFox支持innerText的实现代码_javascript技巧

WBOY
WBOYOriginal
2016-05-16 18:40:471130Durchsuche
为firefox实现innerText属性
很多代码写了又忘忘了又写,很浪费,所以决定养成做笔记的习惯。
知识点:
0、为什么要innerText?因为安全问题
1、为firefox dom模型扩展属性
2、currentStyle属性可以取得实际的style状态
3、IE实现innerText时考虑了display方式,如果是block则加换行
4、为什么不用textContent?因为textContent没有考虑元素的display方式,所以不完全与IE兼容
复制代码 代码如下:



cccddd
eeee
fff







今天在制作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{
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{
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;
}
);
}
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn