js獲取css樣式方法


一、CSS樣式共有三種:內聯樣式(行間樣式)、內部樣式、外部樣式(鏈接式和導入式)

<div id="a" style="width: 100px;height: 100px;"></div>
<style type="text/css">
    #a{
        width: 100px;
        height: 100px;
    }
</style>
<body>
    <div id="a"></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 id="a" style="width: 100px;height: 100px;background-color: blue;"></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 id="a"></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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM