「能不能用 JS 獲取 :before 偽元素?」這是很多人遇到過的困惑。答案是不能——但這不代表我們無法操作它。本文把偽元素的可訪問性邊界、讀取與修改方法系統梳理一遍。
起因通常是有人想用 jQuery 選中偽元素,直覺上 CSS 選擇器這麼強,應該沒問題。但事實是 $(':before')、$(dom).find(':before')、document.querySelector(':before') 全都無效。
原因在于偽元素的定位:::before 和 ::after 用於在元素內容的頭尾插入內容,它們不受文檔約束,也不影響文檔結構,只影響最終的渲染樣式。這些生成的內容不會出現在 DOM 樹中,僅存在於 CSS 渲染層。而 jQuery 的選擇器全部基於 DOM 元素,所以自然選不到它。
一句話總結:偽元素可以被瀏覽器渲染,但它本身不是 DOM 元素,因此 JS 無法直接操作。
共六個:::after、::before、::first-line、::first-letter、::selection、::backdrop。實際項目裡最常用的是前兩個。
語法上,CSS3 建議偽元素使用雙冒號以區分偽類(:hover)與偽元素,多數瀏覽器兩種寫法都支持。唯一的例外是 ::selection,它永遠必須雙冒號。如果需要兼容 IE8(只支持單冒號),保險做法就是全程用單冒號。
雖然拿不到元素,但可以通過 window.getComputedStyle() 拿到它的樣式聲明對象。
語法:window.getComputedStyle(element, pseudoElement)。第一個參數是偽元素所在的真實 DOM 元素,第二個參數是偽元素類型,可選值為 :after、:before、:first-line、:first-letter、:selection、:backdrop。
/* CSS */
#myId:before {
content: "hello world!";
display: block;
width: 100px;
height: 100px;
background: red;
}
<div id="myId"></div>
// JS
var el = document.getElementById('myId');
var beforeStyle = window.getComputedStyle(el, ':before');
console.log(beforeStyle); // CSSStyleDeclaration 對象
console.log(beforeStyle.width); // 100px
console.log(beforeStyle.getPropertyValue('width')); // 100px
console.log(beforeStyle.content); // "hello world!"
兩種取值方式的差別需要注意:
style.backgroundColor;而 getPropertyValue() 要用連字號形式,如 style.getPropertyValue('border-top-color'),且不支援駝峰。float 是個特例,鍵值訪問時不能寫 .float,要用 cssFloat 或 styleFloat。getPropertyValue() 在 IE9+ 及其他現代瀏覽器都支持;IE6~8 可以用 getAttribute() 代替。還有一個很容易踩的坑:偽元素默認是 display: inline。如果沒有顯式設置 display,即使在 CSS 裡寫了 width: 100px,讀出來的 width 仍然是 auto——因為行內元素不接受寬高設置。解法就是把 display 改成 block、inline-block 或其他值。
方法一:更換 class(推薦)。最乾淨的做法,樣式留在 CSS 裡,JS 只負責切換類名。
/* CSS */
.red::before { content: "red"; color: red; }
.green::before { content: "green"; color: green; }
<div class="red">內容內容內容內容</div>
// JS
$('.red').removeClass('red').addClass('green');
方法二:用 CSSStyleSheet 的 insertRule 動態插入規則。
// 兼容 IE
document.styleSheets[0].addRule('.red::before', 'color: green');
// 現代瀏覽器
document.styleSheets[0].insertRule('.red::before { color: green }', 0);
方法三:動態創建 style 標籤。
var style = document.createElement('style');
document.head.appendChild(style);
var sheet = style.sheet;
sheet.addRule('.red::before', 'color: green'); // IE
sheet.insertRule('.red::before { color: green }', 0); // 現代瀏覽器
// 或者用 jQuery 一行搞定
$('<style>.red::before{color:green}</style>').appendTo('head');
方法一:insertRule 替換。
var latestContent = '修改過的內容';
document.styleSheets[0].addRule('.red::before', 'content: "' + latestContent + '"');
document.styleSheets[0].insertRule('.red::before { content: "' + latestContent + '" }', 0);
方法二:借助 data-* 屬性(推薦)。讓 CSS 通過 attr() 讀取元素的自定義屬性,JS 只需改屬性值。
/* CSS */
.red::before { content: attr(data-attr); color: red; }
/* HTML */
<div class="red" data-attr="red">內容內容內容內容</div>
// JS
$('.red').attr('data-attr', 'green');
1. content 的四種取值。直接寫字符串;用 attr() 讀取元素屬性;用 url() 引用圖片等多媒體;用 counter() 配合 counter-increment 做自動編號。
a::after { content: "after content"; }
a::after { content: attr(href); }
a::before { content: url(logo.png); }
h::before { counter-increment: chapter; content: "Chapter " counter(chapter) ". "; }
2. 清除浮動。比額外加一個 div 乾淨得多。
.clear-fix { *overflow: hidden; *zoom: 1; }
.clear-fix::after {
display: table;
content: "";
clear: both;
}
3. 懸停裝飾特效。用兩個偽元素在兩側生成方括號。
a { position: relative; display: inline-block; padding: 5px 10px; text-decoration: none; color: #000; }
a::before, a::after { content: ""; transition: all .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; }
4. 純 CSS 對話框尖角。用邊框三角形拼出來,不需要任何圖片。
.tooltip {
position: relative;
display: inline-block;
padding: 5px 10px;
background: #80D4C8;
}
.tooltip::before {
content: "";
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;
}
偽元素的 content 很強大,但要注意它寫入的內容只存在於 CSS 渲染樹中,不在真實 DOM 裡。這意味著屏幕閱讀器讀不到、搜索引擎抓不到、用戶也無法選中複製。因此凡是與文檔語義相關的內容,都不要放進偽元素,只用於純裝飾。
修改樣式時優先選擇更換 class 的方式。另外兩種插入 CSSStyleSheet 的做法本質是在 JS 裡拼字符串,既不利於樣式與行為分離,拼接過程也容易出錯。修改 content 時同理,用 data-* 屬性配合 attr() 是最優雅的路徑。