Using `.css` for pseudo-elements [duplicate]

柔情痞子 提交于 2019-12-10 18:18:12

问题


Possible Duplicate:
Manipulating CSS :before and :after pseudo-elements using jQuery

I would like to the jQuery equivalent this CSS code:

p:before {
   content: 'Intro!';
}

I've naively tried $('p:before').css('content', 'Intro!'); but it doesn't work.

How can I do pseudo-element CSS modifications using jQuery?


回答1:


You can't.

1) The selector, p:before, is not just a selector -- the psuedo element defines functionality that does not affect the actual selection. What is jQuery supposed to return, all p tags? That's all $(...) does -- it returns a bunch of elements that match your selector. jQuery (Sizzle/querySelectorAll) doesn't know how to fetch :before...

2) Psuedo-element/class behaviour is not available via JS APIs either.

The only way to do something like this, dynamically via JS, would be to create a <style> element, like so:

$('<style>p:before{content:"intro";}</style>').appendTo('head');

May I ask why you want to do this in the first place?




回答2:


You can do this:

$(document).append($("<style>p:before{ content: 'Intro!' } </style>"));


来源:https://stackoverflow.com/questions/7731837/using-css-for-pseudo-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!