innerText屬性用來定義對象要輸出的文本,具體用法以下:javascript
1 <!DOCTYPE> 2 <head> 3 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 4 <script> 5 window.onload = function() 6 { 7 var oTxt = document.getElementById('sp'); 8 oTxt.innerText = "hello"; 9 } 10 </script> 11 </head> 12 13 <body> 14 <span id = "sp"></span> 15 </body> 16 </html>
這時候,span標籤裏的內容爲「hello」,問題在於,這段代碼在IE下運行良好,可是在火狐下卻沒有任何顯示。這是由於innerText的兼容性問題,它在FireFox下是不兼容的,在FireFox下,咱們可使用textContent代替innerText。上述代碼要想在火狐下順利運行,只需將script標籤裏的代碼改成:html
1 window.onload = function() 2 { 3 var oTxt = document.getElementById('sp'); 4 5 if(oTxt.innerText) 6 { 7 oTxt.innerText = "hello"; 8 } 9 else 10 { 11 oTxt.textContent = "hello"; 12 } 13 }
下附淘寶評星功能的代碼,其中包含textContent和innerText的兼容性問題,以及cursor:hand與cursor:pointer的兼容性問題。java
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <script language="JavaScript" type="text/javascript"> 6 function star(n) 7 { 8 var array=new Array(); 9 array[0]=document.getElementById("oneStar"); 10 array[1]=document.getElementById("twoStar"); 11 array[2]=document.getElementById("threeStar"); 12 array[3]=document.getElementById("fourStar"); 13 array[4]=document.getElementById("fiveStar"); 14 15 for(var i=0;i<=n;i++) 16 { 17 if(array[i].innerText) 18 { 19 array[i].innerText="★"; 20 }else 21 { 22 array[i].textContent = "★"; 23 } 24 } 25 for( var j=4;j>n;j--) 26 { 27 if(array[j].innerText) 28 { 29 array[j].innerText="☆"; 30 }else 31 { 32 array[j].textContent="☆"; 33 } 34 } 35 if(document.getElementById("evaluate").innerText) 36 { 37 document.getElementById("evaluate").innerText="您的評價是"+(n+1)+"星"; 38 }else 39 { 40 document.getElementById("evaluate").textContent="您的評價是"+(n+1)+"星"; 41 } 42 } 43 </script> 44 <title>評星</title> 45 </head> 46 <body> 47 <strong>請您對咱們做出評價:</strong> 48 <span id="star"> 49 <span style="cursor:pointer" onclick="star(0)"id="oneStar" >☆</span> 50 <span style="cursor:pointer " onclick="star(1)" id="twoStar" >☆</span> 51 <span style="cursor:pointer " onclick="star(2)" id="threeStar" >☆</span> 52 <span style="cursor:pointer " onclick="star(3)" id="fourStar" >☆</span> 53 <span style="cursor:pointer" onclick="star(4)" id="fiveStar" >☆</span> 54 </span><span id="evaluate"></span> 55 56 </body> 57 </html>