可能重複:
Manipulating CSS :before and :after pseudo-elements using jQuery使用`.css`爲僞元素
我想對jQuery相當於這個CSS代碼:
p:before {
content: 'Intro!';
}
我天真地試過$('p:before').css('content', 'Intro!');
但它不起作用。
我該如何使用jQuery做僞元素CSS修改?
可能重複:
Manipulating CSS :before and :after pseudo-elements using jQuery使用`.css`爲僞元素
我想對jQuery相當於這個CSS代碼:
p:before {
content: 'Intro!';
}
我天真地試過$('p:before').css('content', 'Intro!');
但它不起作用。
我該如何使用jQuery做僞元素CSS修改?
你不能。
1)選擇器p:before
不僅僅是一個選擇器 - psuedo元素定義了不影響實際選擇的功能。什麼是jQuery應該返回,所有p
標籤?這一切都是$(...)
呢 - 它會返回一堆匹配您選擇器的元素。 jQuery(Sizzle/querySelectorAll
)不知道如何獲取:before
...
2)Psuedo-element/class行爲無法通過JS API提供。
做這樣的事情,唯一的方法,通過動態JS,將創建一個<style>
元素,像這樣:
$('<style>p:before{content:"intro";}</style>').appendTo('head');
請問你爲什麼要這樣做擺在首位?
僞**元素**!不要讓這兩個混在一起。 – BoltClock
@BoltClock,謝謝,編輯:) – James
我想要這個的原因是有一個特定的元素上的覆蓋,隨着時間的推移該特定元素的變化。請參閱[this](http://stackoverflow.com/questions/7731523/doing-overlays-without-an-empty-div)問題。 – Randomblue
你可以這樣做:
$(document).append($("<style>p:before{ content: 'Intro!' } </style>"));
Yuck!請不要嵌入'style'。 – Randomblue
@Randomblue:內聯樣式表=/=內聯樣式。 – Blazemonger
這篇文章沒有真正提供答案... – Randomblue
@Randomblue:「你不能用jQuery修改僞元素」而不是答案? – BoltClock
@Sotiris:我不想操縱CSS *元素*本身,只是改變一個CSS *屬性*。 – Randomblue