原生javascript 获得css样式有几种方法?

css 样式分为行内样式和 外部样式:

1、javascript 获得行内样式 :

可以使用  ele.style."属性名称"(如果遇到属性名称带有"-", 需要使用驼峰方法,例如 background-color 改为 backgroundColor);

2、javascript 获得外部样式 ( getComputedStyle 可以获得style 的值也可以获得外部样式表的css)

获得外部样式可以使用浏览器提供的 "window.getComputedStyle( ele,null )"  这里的ele 就是需要操作的对象,第二个参数是指定一个伪元素匹配,常规的元素用不上,直接使用null. 

但是这个getComputedStyle 并不支持IE9 以下的浏览器,但是ie 他有自己支持的方法: ele.currentStyle;

所以为了达到兼容的问题,我们可以自己写好一个通用的函数:

// html 部分

   <style>

   .getdivstyle{

    background: red;

   }

 </style>

 <div id="js-getdivstyle"  class="getdivstyle" style="300px;height:300px;">测试</div>

// javascript 部分

<script>

 // js调用部分

 var getDivStyle = getId("js-getdivstyle");

 getStyle( getDivStyle, "width");

 getStyle( getDivStyle, "background-color"); // 这里的属性选择驼峰或者是默认加“-”的属性都可以,但是不能直接使用缩写 “background”

 // 封装好的获取样式函数 

 function getStyle(obj,attr){

  if(window.getComputedStyle){

   return window.getComputedStyle(obj,null)[attr];

  }else{

   return obj.currentStyle[attr];

  }

 }

 // 封装好的获取元素id

 function getId(idName){

  return document.getElementById(idName);

 }

</script>

 题外话  

ele.style.属性名 和 ele.cssText 以及 getComputedStyle(obj,null)  有什么区别

1、ele.style.属性名  这里获得的style 可以获得属性值,也可以设置修改他, 例如: ele.style.left = 10 + "px";  

2、ele.cssText 其实跟style差不多,只不过它是获得多个css样式。例如 : ele.style.cssText = "font-size:16px; height:250px"   也是生成在行内样式中。

3、 getComputedStyle(obj,null) 只能获取值不能修改,并且返回的css是一个 CSSStyleDeclaration 对象集合。详细见: https://developer.mozilla.org/zh-CN/docs/Web/API/CSSStyleDeclaration

原文地址:https://www.cnblogs.com/Shinnosuke/p/5563846.html