獲取行內樣式
> 注:只能獲取和設置行內樣式
1. 獲取值:obj.style.屬性名
2. 設置值:obj.style.屬性名 = 屬性值;
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>Document</title> 7 </head> 8 <body> 9 <div id='div1' style="color: red;"></div> 10 <script type="text/javascript"> 11 let obj = document.getElementById('div1') ; 12 console.log(obj.style.color); // red 13 14 obj.style.color = 'yellow'; 15 console.log(obj.style.color); // yellow 16 </script> 17 </body> 18 </html>
獲取全部樣式
> 注:可以設置全部樣式(行內樣式、內部樣式、外部樣式),但不能設置值
1. 獲取值:window.getComputedStyle(元素對象[, null/偽元素]); 如果不存在偽元素,第二個屬性值可以省略不寫
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>Document</title> 7 <style type="text/css"> 8 #div1 { 9 width: 500px; 10 } 11 </style> 12 </head> 13 <body> 14 <div id='div1' style="color: red;"></div> 15 <script type="text/javascript"> 16 let obj = document.getElementById('div1') ; 17 console.log(window.getComputedStyle(obj).color); // rgb(255, 0, 0) 18 console.log(window.getComputedStyle(obj).width); // 500px 19 </script> 20 </body> 21 </html>
該屬性在ie8以下無效,ie8以下可以通過:obj.currentStyle('color') 來獲取
js獲取設置css屬性兼容性寫法:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>Document</title> 7 <style type="text/css"> 8 #div1 { 9 width: 500px; 10 } 11 </style> 12 </head> 13 <body> 14 <div id='div1' style="color: red;"></div> 15 <script type="text/javascript"> 16 /* 17 * 參數列表: 18 * ele:dom對象 19 * prop:屬性名 20 * val:屬性值 21 */ 22 function getAndSetStyle(ele, prop, val) { 23 if(val) { 24 // 設置值 25 ele.style[prop] = val; 26 }else { 27 // 兼容ie8以下 28 if(ele.currentStyle) { 29 return ele.currentStyle[prop]; 30 }else { 31 return window.getComputedStyle(obj)[prop]; 32 } 33 } 34 } 35 36 var obj = document.getElementById("div1"); 37 console.log(getAndSetStyle(obj, 'color')); // red 38 console.log(getAndSetStyle(obj, 'width')); // 500px 39 40 getAndSetStyle(obj, 'height', '200px'); 41 console.log(getAndSetStyle(obj, 'height')); // 200px 42 </script> 43 </body> 44 </html>