js获取css样式方法

一、CSS样式共有三种:内联样式(行间样式)、内部样式、外部样式(链接式和导入式)

<div  ></div>
<style type="text/css">
    #a{
        width: 100px;
        height: 100px;
    }
</style>
<body>
    <div ></div>
</body>
<!-- 外部CSS样式 -->
<!-- 链接式 -->
<link rel="stylesheet" type="text/css" href="css/temp.css"/>
<style type="text/css">
    <!-- 导入式 -->
    @import url("css/style.css");
</style>

优先级:一般情况下:内联样式 > 内部样式 > 外部样式

特殊情况下:当外部样式放在内部样式之后,外部样式将覆盖内部样式。

<style type="text/css">
    #a{
        width: 200px;
        height: 200px;
        background-color: red;
    }
</style>
<link rel="stylesheet" type="text/css" href="css/temp.css"/>

二、js获取css样式

1、内联样式(行间样式)的获取

<div  ></div>
function temp(){
    var a=document.getElementById("a");
    var aColor=a.style.backgroundColor;
    var aWidth=a.style["width"];
    alert(aColor+"  "+aWidth);
//    rgb(0,0,255)  100px
}

2、内部样式的获取

<style type="text/css">
    #a{
        width: 200px;
        height: 200px;
        background-color: red;
    }
</style>
<body>
    <div ></div>
</body>
function temp(){
//  非IE浏览器
    var a=document.getElementById("a");
    var aStyle=getComputedStyle(a);
    var aColor=aStyle.backgroundColor;
    var aWidth=aStyle["width"];
    alert(aColor+"  "+aWidth);
//  rgb(255,0,0)  200px
//  IE浏览器
//  var a=document.getElementById("a");
//  var aStyle=a.currentStyle;
//  var aColor=aStyle.backgroundColor;
//  var aWidth=aStyle["width"];
//  alert(aColor+"  "+aWidth);
//  red  200px
}

3、外部样式的获取(同内部样式)

<!-- css文件 -->
#a{
    width: 300px;
    height: 300px;
    background-color: #4F5F6F;
}