JS获取CSS样式:style、getComputedStyle与currentStyle详解

作者:白露时间:2026-10-29 20:38:29浏览:217

本文详细解析JavaScript中获取CSS样式的三种主要方式:内联的style属性、IE特有的currentStyle以及标准的getComputedStyle。重点讲解float等兼容性问题,以及getPropertyValue和getAttribute方法的正确用法,帮助开发者在不同浏览器环境下准确获取最终计算后的样式值。

CSS样式分类与获取基础

CSS样式主要包含三种形式:内嵌样式直接写在HTML标签内部,仅对该标签生效;内部样式定义在HTML文档的head部分,作用于当前网页;外部样式表则通过将样式写入独立的.css文件,并在多个网页中引用该文件,实现样式的复用与管理。

getComputedStyle与currentStyle对比

getComputedStyle函数用于获取元素当前最终应用的CSS属性值,返回一个CSSStyleDeclaration对象。而在IE浏览器中,currentStyle属性同样用于返回CSS样式对象,但它是IE特有的实现方式。

各浏览器获取非内嵌样式的方法

获取DOM对象后,可通过element.style直接读取内嵌样式;对于非内嵌样式,IE浏览器使用element.currentStyle进行获取;非IE浏览器(如Firefox、Chrome等)则使用window.getComputedStyle(element, 伪类)或document.defaultView.getComputedStyle(element, 伪类)。需要注意的是,在Gecko 2.0(即Firefox 4、Thunderbird 3.3、SeaMonkey 2.1)之前的版本中,第二个参数“伪类”为必填项,若非伪类需设置为null,后续版本可省略该参数。

示例HTML包含两种CSS样式:id为tag的div采用内嵌样式,而id为test的div采用内部样式表定义。


<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="Generator" content="EditPlus®">
    <meta name="Author" content="Yvette Lau">
    <meta name="Keywords" content="关键字">
    <meta name="Description" content="描述">
    <title>Document</title>
    <style>
      #test{
        width:500px;
        height:300px;
        background-color:#CCC;
        float:left;
      }
    </style>
  </head>
  <body>
    <div id = "test"></div>
    <div id = "tag" style = "width:500px; height:300px;background-color:pink;"></div>
  </body>
</html>

接下来展示具体的JavaScript代码实现部分。


<script type = "text/javascript">
  window.onload = function(){
    var test = document.getElementById("test");
    var tag = document.getElementById("tag");

    //CSS样式对象:CSS2Properties{},CSSStyleDeclaration
    console.log(test.style); //火狐返回空对象CSS2Properties{},谷歌返回空对象CSSStyleDeclaration{} 
    console.log(tag.style); //返回CSS2Properties{width:"500px",height:"300px",background-color:"pink"}
    //element.style获取的是内嵌式的style,如果不是内嵌式,则是一个空对象

    console.log(tag.style.backgroundColor);//pink
    console.log(tag.style['background-color']);//pink
    //获取类似background-color,border-radius,padding-left类似样式的两种写法啊

    console.log(test.currentStyle) //火狐和谷歌为Undefined,IE返回CSS对象
    console.log(window.getComputedStyle(test,null))//谷歌返回CSSStyleDeclaration{……} ,火狐返回CSS2Properties{……}
    console.log(window.getComputedStyle(test))
    //效果同上,但是在Gecko 2.0 (Firefox 4/Thunderbird 3.3/SeaMonkey 2.1) 之前,第二个参数“伪类”是必需的(如果不是伪类,设置为null)

    console.log(test.currentStyle.width);//500px(IE)
    console.log(window.getComputedStyle(test).width); //500px;
    console.log(window.getComputedStyle(test)['width']);//500px;
    //document.defaultView.getComputedStyle(element,null)[attr]/window.getComputedStyle(element,null)[attr]   
  }
</script>

上述示例主要用于验证前文关于样式获取方式的论述是否准确。

为了简化开发流程,我们可以对样式获取逻辑进行封装。


function getStyle(element, attr){
      if(element.currentStyle){
        return element.currentStyle[attr];
      }else{
        return window.getComputedStyle(element,null)[attr];
      }
    }
    console.log(getStyle(test,"cssFloat"));//left
    console.log(getStyle(test,"float"));  //left,早前FF和chrome需要使用cssFloat,不过现在已经不必
    console.log(getStyle(test,"stylefloat"));//火狐和谷歌都是undefined
    console.log(getStyle(test,"styleFloat")); //IE9以下必须使用styleFloat,IE9及以上,支持styleFloat和cssFloat

    console.log(window.getComputedStyle(test).getPropertyValue("float"))

float属性兼容性与通用访问方法

针对float属性,IE浏览器使用styleFloat,而早期Firefox和Chrome使用cssFloat。目前Firefox和Chrome已支持直接使用float,其他属性也存在类似差异。为避免记忆这些兼容性问题,可以引入访问CSS样式对象的两种通用方法:getPropertyValue和getAttribute。

现代浏览器与IE9+的getPropertyValue用法

在IE9及以上浏览器及其他现代浏览器中,推荐使用getPropertyValue方法。例如:window.getComputedStyle(element, null).getPropertyValue(“float”)或element.currentStyle.getPropertyValue(“float”)。需注意,getPropertyValue不支持驼峰命名法,如获取背景色应使用“background-color”而非“backgroundColor”。该方法兼容IE9及以上、Firefox、Chrome、Safari和Opera。

IE6~8的getAttribute兼容处理

对于IE6至IE8浏览器,需使用getAttribute方法来访问CSS样式对象的属性。

在IE6~8中,element.currentStyle.getAttribute(“float”)可直接使用,无需写成styleFloat。若获取backgroundColor,属性名需采用驼峰写法(如“backgroundColor”),否则IE6可能不支持;若忽略IE6,则可使用“background-color”。

以上内容涵盖了JS获取CSS样式的核心方法,旨在帮助开发者轻松处理不同浏览器环境下的样式获取问题。

作者最新文章