JS控制偽元素的方法匯總

字號(hào):


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