JS兼用IE8的通過class名獲取CSS對象組
轉自:Garon_InE
原生js方法“document.getElementsByClassName”在ie8及其以下瀏覽器中不能使用,所以寫了一個兼容IE的方法。
完整的頁面代碼如下:
testJsGetCssClass.html
1 <html> 2 <head> 3 <style type="text/css"> 4 .test_class_div { 5 font-size: 14px; 6 border: 1px solid #ccc; 7 margin: 10px; 8 padding: 5px; 9 font-weight: bold; 10 color: red; 11 } 12 </style> 13 14 <script> 15 /** 16 *打印js對象詳細信息 17 */ 18 function alertObj(obj) 19 { 20 var description = ""; 21 for ( var i in obj) 22 { 23 var property = obj[i]; 24 description += i + " = " + property + "\n"; 25 } 26 alert(description); 27 } 28 29 /** 30 *通過class名和標簽名獲取css樣式對象組 31 */ 32 function getClassNames(classStr, tagName) 33 { 34 if (document.getElementsByClassName) 35 { 36 return document.getElementsByClassName(classStr) 37 } else 38 { 39 //為了兼容ie8及其以下版本的方法 40 var nodes = document.getElementsByTagName(tagName), ret = []; 41 for (i = 0; i < nodes.length; i++) 42 { 43 if (hasClass(nodes[i], classStr)) 44 { 45 ret.push(nodes[i]) 46 } 47 } 48 return ret; 49 } 50 } 51 52 /** 53 *判斷節點class存在性 54 */ 55 function hasClass(tagStr, classStr) 56 { 57 //這個正則表達式是因為class可以有多個,判斷是否包含 58 var arr = tagStr.className.split(/\s+/); 59 for ( var i = 0; i < arr.length; i++) 60 { 61 if (arr[i] == classStr) 62 { 63 return true; 64 } 65 } 66 return false; 67 } 68 </script> 69 </head> 70 <body> 71 <div class="test_class_div">11111111</div> 72 <div class="test_class_div">22222222</div> 73 <div class="test_class_div">33333333</div> 74 <script> 75 //由于加載順序,獲取對象的代碼應寫在對象已加載之后 76 var divs = getClassNames('test_class_div', 'div'); 77 if (null != divs) 78 { 79 alertObj(divs); 80 //遍歷對象,改其css樣式 81 for ( var i = 0; i < divs.length; i++) 82 { 83 divs[i].style.color = "blue"; 84 } 85 } 86 </script> 87 </body> 88 </html>
運行結果:
初始字體顏色為紅色,通過對象組修改后為藍色。
firefox:


ie8:


畢竟人生那么長,如果不喜歡做開發,就別和bug較勁了。

浙公網安備 33010602011771號