擷取css樣式,style、getComputedStyle及currentStyle的區別

來源:互聯網
上載者:User

標籤:ref   屬性   asc   pre   win   style   font   load   alert   

樣式表有三種:

內嵌樣式:<div id="box" style="color:red">box</div>,style寫在html中的為內嵌樣式;

內聯樣式:

<style>
#box{
    font-size: 25px;
    background-color: #ccc;
}
</style>

在html頁中直接寫入<style></style>的為內聯樣式;

外部樣式:<link rel="stylesheet" href="css/style.css" />這種為外部樣式。

現在來測試一個小例子:

<style>#box{   font-size: 25px;   background-color: #ccc;}</style>
<div id="box" style="color:red">box</div>

js代碼:

window.onload=function(){        var box=document.getElementById(‘box‘);        alert(box.style.color);  //彈出red   element.style[attr]對內嵌樣式有效        alert(box.style.fontSize);   //彈出空   從這裡可以看出element.style[attr]只對內聯樣式無效        alert(isStyle(box,‘color‘));   //使用isStyle方法,彈出rgb(255,0,0)        alert(isStyle(box,‘fontSize‘));  //使用isStyle方法,彈出25px}/*通過元素節點和屬性擷取屬性值*/function isStyle(ele,attr){        if(window.getComputedStyle!=‘undefined‘){   //相容firefox        return window.getComputedStyle(ele,null)[attr];        }else if(ele.currentStyle!=‘undefined‘){    //相容IE                return ele.currentStyle[attr];        }}

要想擷取內部樣式以及外部樣式需要通過getComputedStyle和currentStyle來擷取,當然也可以擷取內嵌樣式。

擷取css樣式,style、getComputedStyle及currentStyle的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.