Javascript擷取CSS虛擬元素的屬性

來源:互聯網
上載者:User

CSS虛擬元素非常強大,它經常被用來建立CSS三角形提示,使用CSS虛擬元素可以實現一些簡單的效果但又不需要增加額外的HTML標籤。有一點就是Javascript無法擷取到這些CSS屬性值,但現在有一種方法可以擷取到:

看看下面的CSS代碼:

copytext

 代碼如下 複製代碼
.element:before {
    content: 'NEW';
    color: rgb(255, 0, 0);
}.element:before {
 content: 'NEW';
 color: rgb(255, 0, 0);
}

為了擷取到.element:before的顏色屬性,你可以使用下面的代碼:

 代碼如下 複製代碼
copytext
var color = window.getComputedStyle(
    document.querySelector('.element'), ':before'
).getPropertyValue('color')var color = window.getComputedStyle(
 document.querySelector('.element'), ':before'
).getPropertyValue('color')

把虛擬元素作為第二個參數傳到window.getComputedStyle方法中就可以擷取到它的CSS屬性

了。把這段代碼放到你的工具函數集裡面去吧。隨著虛擬元素被越來越多的瀏覽器支援,這個方法會很有用的。

譯者註:window.getComputedStyle方法在IE9以下的瀏覽器不支援,getPropertyValue必須配合getComputedStyle方法一起使用。IE支援CurrentStyle屬性,但還是無法擷取虛擬元素的屬性。

準確擷取指定元素 CSS 屬性值的方法。 

 代碼如下 複製代碼

<script type="text/javascript">
function getStyle( elem, name )
{
    //如果該屬性存在於style[]中,則它最近被設定過(且就是當前的)
    if (elem.style[name])
    {
        return elem.style[name];
    }
    //否則,嘗試IE的方式
    else if (elem.currentStyle)
    {
        return elem.currentStyle[name];
    }
    //或者W3C的方法,如果存在的話
    else if (document.defaultView && document.defaultView.getComputedStyle)
    {
        //它使用傳統的"text-Align"風格的規則書寫方式,而不是"textAlign"
        name = name.replace(/([A-Z])/g,"-$1");
        name = name.toLowerCase();
        //擷取style對象並取得屬性的值(如果存在的話)
        var s = document.defaultView.getComputedStyle(elem,"");
        return s && s.getPropertyValue(name);
    //否則,就是在使用其它的瀏覽器
    }
    else
    {
        return null;
    }
}
</script>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.