JS获取元素CSS值

一、getComputedStyle

  getComputedStyle 是一个可以获取当前元素所有最终使用的CSS属性值。返回的是一个CSS样式声明对象([object CSSStyleDeclaration]),只读。

  语法如下:

var style = window.getComputedStyle("元素", "伪类");
//
var dom = document.getElementById("test");
var style = window.getComputedStyle(dom , ":after");

//获取属性可以用 getPropertyValue (不驼峰 IE9+),getAttribute(驼峰)

style.getAttribute("backgroundColor");
style.getPropertyValue("border-top-left-radius");

  Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) 之前,第二个参数“伪类”是必需的(如果不是伪类,设置为null);

  

  getComputedStyle IE6~8是不支持的。

  IE可以用CurrentStyle,它是IE浏览器自娱自乐的一个属性

  例如,我们要获取一个元素的高度,可以类似下面的代码:

alert((element.currentStyle? element.currentStyle : window.getComputedStyle(element, null)).height);

  

二、style

  element.style 可读可写。

  getComputedStyle 方法获取的是最终应用在元素上的所有CSS属性对象(包括默认),而element.style只能获取元素style属性中的CSS样式。

三、getBoundingClientRect()

  

var box=document.getElementById('box');         // 获取元素

alert(box.getBoundingClientRect().top);         // 元素上边距离页面上边的距离

  IE8一下只有上下左右可获取到,默认坐标从(2,2)开始计算,

var right =  box.getBoundingClientRect().right;
var left = box.getBoundingClientRect().left;

var width = right-left;
原文地址:https://www.cnblogs.com/hjsblogs/p/6097685.html