现在的位置: 首页 > web前端 > 正文

currentstyle属性的作用

2020年07月17日 web前端 ⁄ 共 907字 ⁄ 字号 评论关闭

  CurrentStyle返回所有样式声明(包括内部、外部、内联)按css层叠规则作用于元素的最终样式。只有IE和Opera支持使用CurrentStyle获取的元素计算后的样式。getComputeStyle()方法可以获取当前元素所使用的css属性值。


  currentstyle属性的作用是什么?


  该属性是一个对象,也是计算后的样式的属性值对的集合。为了兼容性我们可以将其封装改写一下,提供一个统一的方法getCurrentStyle(node),如下:


  functiongetCurrentStyle(node){


  varstyle=null;


  if(window.getComputedStyle){


  style=window.getComputedStyle(node,null);


  }else{


  style=node.currentStyle;


  }


  currentStyle对象


  vardiv=window.getComputeStyle("div",null).color;//第一个参数为目标元素,第二个参数为伪类(必需,没有伪类设为null)


  与style对象的区别:


  getComputeStyle()是只读,只能获取不能设置,style能读能设;


  对于一个没有设定任何样式的元素,getComputedStyle()返回对象中的length属性值,而style对象中length是0。


  不同的浏览器对currentStyle对象支持有差异,需要兼容处理。


  vardiv=document.getElementById('div');


  varcolorStr=null;


  if(div.currentStyle){//兼容IE


      colorStr=div.currentStyle;


  }else{


  colorStr=window.getComputedStyle(div,null);


  }


  varcol=colorStr.color;//得到div的color属性值


  总之,CurrentStyle给大家简单的介绍了一些,希望大家多看看。

抱歉!评论已关闭.