解决firefox不支持innerText的办法

时间:2024-01-17 17:16:56
js代码:
<script>
window.onload = function(){
if(window.navigator.userAgent.toLowerCase().indexOf("msie")==0){ //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].textContent;
else if(childS[i].nodeType==3)
anyString += childS[i].nodeValue;
}
return anyString;
}
);
HTMLElement.prototype.__defineSetter__( "innerText",
function(sText){
this.textContent=sText;
}
);
};
var test = document.getElementById("test");
var innerText_s = test.innerText;
if( innerText_s == undefined ){
alert( test.textContent ); // firefox
}else{
alert( test.innerText);
}; } </script>

html代码

<div id="test">
      <span style="color:red">test1</span> test2
</div>