天天看点

js获取css样式的解决方法

js获取css样式的方法

  • 以获取元素高度为例,有以下几种方法。(var test=document.getElementbyId("test")????
    1. test.offseHeight 相当于内容区高度+上下边界+上下内边距
    2. test.clientHeight 相当于内容区高度+上下内边距
    3. (推荐使用)window.getComputedStyle(test).getPropertyValue('height');

      getComputedStyle

      方法取得了元素的所有样式
    4. 当test设置了内联样式且该内联样式包含高度是,才能使用test.style.height

获取最终应用在元素上的所有CSS属性对象的意思是,如果没有给元素设置任何样式,也会把浏览器默认的样式返回来。

1、ele.style 在学习DOM的时候就看到通过ele.style来获取元素样式值,但是有时候获取的并非是节点的样式值,而是空值。这是因为ele.style只能获取写在元素标签中的style属性里的样式值,无法获取到定义在和通过加载进来的样式属性

例子:

var test = document.getElementById("test");
//获取节点的color
 
test.style.color;
           

2、getComputedStyle() getComputedStyle是一个可以获取当前元素所有最终使用的CSS属性值。

语法如下:

window.getComputedStyle("元素", "伪类");
           
var test = document.getElementById("test"),
demo = window.getComputedStyle(test, null); 
 
//获取节点的color
 
 demo.color