css中样式属性的获取

来源:互联网 发布:安徽网络作家协会申请 编辑:程序博客网 时间:2024/05/20 14:19

_.style只能获取元素的内联样式,内部样式和外部样式使用style是获取不到的。

_.currentStyle可以弥补style的不足,但是只适用于IE

_.getComputedStylecurrentStyle作用相同,但是适用于FFoperasafarichrome

getComputedStyle:

 

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

 

简单来说 读出你八辈祖宗的一个方法。

 

语法: window.getComputedStyle(dom, '伪元素')

 

伪元素 其实就是 ::before :: after :: first-line::first-letter ::content 等等

 

伪类 :hover :link :first-child :active 等等

 

用法

 

var oImg =document.getElementById('photo');

 

window.getComputedStyle(oImg,null).height;

 

dom.style(获取内联样式)

说明: 获取元素style属性中的CSS样式, 简单说就是 能读能写 只能读你的外表

 

语法 dom.style.样式名称

 

用法:

<img  id =”photo” style=”height:  ”/>

var oImg =document.getElementById('photo');

 

oImg.style.height;  //获取内联样式



currentStyle (IE)

 

说明: 返回的是元素当前应用的最终CSS属性值(包括外链CSS文件,页面中嵌入的<style>属性等)与getComputedStyle那个读你八辈祖宗的很像,但是不能获取伪元素。且他们获取的属性也有很大差异。

 

语法 element.currentStyle.样式

 

用法

 

var oImg =document.getElementById('photo');

 

oImg.currentStyle.height;  // 只能获取css 样式表的

 

getPropertyValue和getAttribute(通过元素节点调用)

 

说明 :可以获取CSS样式申明对象上的属性值(直接属性名称),

 

getPropertyValue可以不用驼峰,直接用其属性名

 

getAttribute主要是为了兼容IE获取属性值,需要驼峰的写法

 

语法

 

getPropertyValue("background-color")

 

getAttribute("backgroundColor")

 

用法

 

var oImg =document.getElementById('photo');

 

var oStyle = oImg.currentStyle? oImg.currentStyle :window.getComputedStyle(oImg, null);

 

oStyle.getPropertyValue("background-color")

 

oStyle.getAttribute("backgroundColor")//只能在IE中用

 

总结

 

如果我想获取某个属性值 比如高度 ?

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

 

如果是复合的某个属性获取?

 

(oImg.currentStyle?oImg.currentStyle:window.getComputedStyle(oImg,null)).getPropertyValue("background-color")

 

如果我想给这个属性重新设置这个高度?

 

可以先用上面方法取到,然后用

 

dom.style.height= XX + 'px';

 

如果是复合的属性值,请注意是驼峰的写法!

原创粉丝点击