標籤:return span char asc style 根據id擷取 attr head 測試
1 <html> 2 <head> 3 <meta charset="UTF-8"> 4 <title>CSS樣式的擷取和設定:簡單版</title> 5 <style type="text/css"> 6 #div { 7 width: 100px; 8 height: 100px; 9 background: pink; 10 } 11 </style> 12 <script type="text/javascript"> 13 //根據id擷取元素 14 function $(id) { 15 return document.getElementById(id); 16 } 17 //擷取樣式 18 function getStyle(obj, attr) { 19 //哪個對象obj 20 //哪個屬性attr 21 //相容IE 22 if (obj.currentStyle) { 23 return obj.currentStyle[attr]; 24 } 25 else { 26 //相容Google Firefox 27 return getComputedStyle(obj, false)[attr]; 28 } 29 } 30 31 //擷取或者設定CSS的屬性 32 function css(obj, attr, value) { 33 //擷取CSS的數值 34 if (arguments.length == 2) { 35 return getStyle(obj, attr); 36 } 37 //設定CSS的數值 38 if (arguments.length == 3) { 39 obj.style[attr] = value; 40 } 41 } 42 //調用CSS()方法,進行測試 43 window.onload = function() { 44 css($("div"), "width", “200px”); 45 } 46 // 最後可以把這寫在一起,一個函數就搞定47 function css(obj,attr,value){48 var getStyle = obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj,false)[attr];49 if(arguments.length === 2){50 return getStyle;51 52 }else if(arguments.length === 3){53 obj.style[attr] = value;54 }55 }56 </script> 57 </head> 58 <body> 59 <div id="div"></div> 60 </body>61 </html>
關於擷取、設定css樣式封裝的函數入門版