JS控制偽元素的方法匯總

字號:


    本文給大家介紹js控制偽元素的方法匯總,本文涉及到獲取偽元素屬性值的方法,本文介紹的非常詳細,具有參考借鑒價值,感興趣的朋友一起學習吧
    一. 緣由:
    本文源于在OSC社區(qū)中,有人提問如何用jq獲取偽元素。我第一想法是強大的CSS Query應該可以獲取偽元素吧。
    然而事實上,CSS Query并不能。即我們不能通過$(“:before”)、$(dom).find(“:before”)或document.querySelector(“:before”)來獲取:before偽元素。
    為此,我不得不重新了解偽元素(Pseudo-elements)。為什么不能用JS直接獲取偽元素呢?
    譬如::before和::after偽元素,用于在CSS渲染中向元素的頭部或尾部插入內(nèi)容,它們不受文檔約束,也不影響文檔本身,只影響最終樣式。這些添加的內(nèi)容不會出現(xiàn)在DOM中,僅僅是在CSS渲染層中加入。
    事實上, 偽元素可以被瀏覽器渲染,但本身并不是DOM元素。它不存在于文檔中,所以JS無法直接操作它。 而jQuery的選擇器都是基于DOM元素的,因此也并不能直接操作偽元素。
    那該怎樣操作偽元素的樣式呢?
    為此,我決定好好總結(jié)一下JS控制偽元素的方法,方便以后查用。
    二. 偽元素有哪些:
    首先,先簡單說一下偽元素都有哪些。偽元素有六個,分別是 ::after、::before、::first-line、::first-letter、::selection、::backdrop 。
    在各大網(wǎng)頁中最常用的偽元素,是::after和::before。
    這幾個偽元素的語意可參考我的另外一篇文章《CSS偽元素選擇器 總結(jié)》。
    在CSS3中,建議偽元素使用兩個冒號(::)語法,而不是一個冒號 (:),目的是為了區(qū)分偽類和偽元素。大多數(shù)瀏覽器都支持這兩種表示語法。只有 ::selection 永遠只能以兩個冒號開頭(::)。因為IE8只支持單冒號的語法,所以,如果你想兼容IE8,保險的做法是使用單冒號。
    三. 獲取偽元素的屬性值:
    獲取偽元素的屬性值可以使用 window.getComputedStyle() 方法,獲取偽元素的CSS樣式聲明對象。然后利用getPropertyValue方法或直接使用鍵值訪問都可以獲取對應的屬性值。
    語法:window.getComputedStyle(element[, pseudoElement])
    參數(shù)如下:
    element(Object):偽元素的所在的DOM元素;
    pseudoElement(String):偽元素類型。可選值有:”:after”、”:before”、”:first-line”、”:first-letter”、”:selection”、”:backdrop”;
    舉個栗子:
    // CSS代碼
    #myId:before {
    content: "hello world!";
    display: block;
    width: 100px;
    height: 100px;
    background: red;
    }
    // HTML代碼
    <div id="myId"></div>
    // JS代碼
    var myIdElement = document.getElementById("myId");
    var beforeStyle = window.getComputedStyle(myIdElement, ":before");
    console.log(beforeStyle); // [CSSStyleDeclaration Object]
    console.log(beforeStyle.width); // 100px
    console.log(beforeStyle.getPropertyValue("width")); // 100px
    console.log(beforeStyle.content); // "hello world!"
    備注:
    1.getPropertyValue()和直接使用鍵值訪問,都可以訪問CSSStyleDeclaration Object。它們兩者的區(qū)別有:
    對于float屬性,如果使用鍵值訪問,則不能直接使用getComputedStyle(element, null).float,而應該是cssFloat與styleFloat;
    直接使用鍵值訪問,則屬性的鍵需要使用駝峰寫法,如:style.backgroundColor;
    使用getPropertyValue()方法不必可以駝峰書寫形式(不支持駝峰寫法),例如:style.getPropertyValue(“border-top-color”);
    getPropertyValue()方法在IE9+和其他現(xiàn)代瀏覽器中都支持;在IE6~8中,可以使用getAttribute()方法來代替;
    2.偽元素默認是”display: inline”。如果沒有定義display屬性,即使在CSS中顯式設置了width的屬性值為固定的大小如”100px”,但是最后獲取的width值仍是”auto”。這是因為行內(nèi)元素不能自定義設置寬高。解決辦法是給偽元素修改display屬性為”block”、”inline-block”或其他。
    四. 更改偽元素的樣式:
    方法1. 更換class來實現(xiàn)偽元素屬性值的更改:
    舉個栗子:
    // CSS代碼
    .red::before {
    content: "red";
    color: red;
    }
    .green::before {
    content: "green";
    color: green;
    }
    // HTML代碼
    <div>內(nèi)容內(nèi)容內(nèi)容內(nèi)容</div>
    // jQuery代碼
    $(".red").removeClass('red').addClass('green');
    方法2. 使用CSSStyleSheet的insertRule來為偽元素修改樣式:
    舉個栗子:
    document.styleSheets[0].addRule('.red::before','color: green'); // 支持IE document.styleSheets[0].insertRule('.red::before { color: green }', 0); // 支持非IE的現(xiàn)代瀏覽器
    方法3. 在 <head> 標簽中插入 <style> 的內(nèi)部樣式:
    var style = document.createElement("style");
    document.head.appendChild(style);
    sheet = style.sheet;
    sheet.addRule('.red::before','color: green'); // 兼容IE瀏覽器
    sheet.insertRule('.red::before { color: green }', 0); // 支持非IE的現(xiàn)代瀏覽器
    或者用jQuery:
    $('<style>.red::before{color:green}</style>').appendTo('head');
    五. 修改偽元素的content的屬性值:
    方法1. 使用CSSStyleSheet的insertRule來為偽元素修改樣式:
    var latestContent = "修改過的內(nèi)容";
    var formerContent = window.getComputedStyle($('.red'), '::before').getPropertyValue('content'); document.styleSheets[0].addRule('.red::before','content: "' + latestContent + '"'); document.styleSheets[0].insertRule('.red::before { content: "' + latestContent + '" }', 0);
    方法2. 使用DOM元素的data-*屬性來更改content的值:
    // CSS代碼
    .red::before {
    content: attr(data-attr);
    color: red;
    }
    // HTML代碼
    <div data-attr="red">內(nèi)容內(nèi)容內(nèi)容內(nèi)容</div>
    // JacaScript代碼
    $('.red').attr('data-attr', 'green');
    六. :before和:after偽元素的常見用法總結(jié):
    1. 利用content屬性,為元素添加內(nèi)容修飾:
    1) 添加字符串:
    使用引號包括一段字符串,將會向元素內(nèi)容中添加字符串。栗子:
    a:after { content: "after content"; }
    2) 使用attr()方法,調(diào)用當前元素的屬性的值:
    栗子:
    a:after { content: attr(href); }
    a:after { content: attr(data-attr); }
    3)使用url()方法,引用多媒體文件:
    栗子:
    a::before { content: url(logo.png); }
    4) 使用counter()方法,調(diào)用計時器:
    栗子:
    h:before { counter-increment: chapter; cotent: "Chapter " counter(chapter) ". " }
    2. 清除浮動:
    .clear-fix { *overflow: hidden; *zoom: 1; }
    .clear-fix:after { display: table; content: ""; width: 0; clear: both; }
    3. 特效妙用:
    // CSS代碼
    a {
    position: relative;
    display: inline-block;
    text-decoration: none;
    color: #000;
    font-size: 32px;
    padding: 5px 10px;
    }
    a::before, a::after {
    content: "";
    transition: all 0.2s;
    }
    a::before {
    left: 0;
    }
    a::after {
    right: 0;
    }
    a:hover::before, a:hover::after {
    position: absolute;
    }
    a:hover::before { content: "\5B"; left: -20px; }
    a:hover::after { content: "\5D"; right: -20px; }
    // HTML代碼
    <a href="#">我是個超鏈接</a>
    4. 特殊形狀的實現(xiàn):
    舉個栗子:(譬如對話氣泡)
    // CSS代碼
    .tooltip {
    position: relative;
    display: inline-block;
    padding: 5px 10px;
    background: #80D4C8;
    }
    .tooltip:before {
    content: "";
    display: block;
    position: absolute;
    left: 50%;
    margin-left: -5px;
    bottom: -5px;
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 5px solid #80D4C8;
    }
    // HTML代碼
    <div>I'm a tooltip.</div>
    :before 和 :after 偽元素結(jié)合更多CSS3強大的特性,還可完成非常多有趣的特效和 hack ,這里權(quán)當拋磚引玉。
    六. 一點小小建議:
    偽元素的content屬性很強大,可以寫入各種字符串和部分多媒體文件。但是偽元素的內(nèi)容只存在于CSS渲染樹中,并不存在于真實的DOM中。所以為了SEO優(yōu)化,最好不要在偽元素中包含與文檔相關的內(nèi)容。
    修改偽元素的樣式,建議使用通過更換class來修改樣式的方法。因為其他兩種通過插入行內(nèi)CSSStyleSheet的方式是在JavaScript中插入字符代碼,不利于樣式與控制分離;而且字符串拼接易出錯。
    修改偽元素的content屬性的值,建議使用利用DOM的data-*屬性來更改。
    以上所述是小編給大家介紹的JS控制偽元素的方法匯總,希望對大家有所幫助!