js中获取css样式

获取行内样式

> 注:只能获取和设置行内样式

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>
原文地址:https://www.cnblogs.com/mengbing/p/12491777.html