jquery - 使用 `.css` 作为伪元素

标签 jquery css pseudo-element

<分区>

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

我想要 jQuery 等效于此 CSS 代码:

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

我曾天真地尝试过 $('p:before').css('content', 'Intro!'); 但它不起作用。

如何使用 jQuery 进行伪元素 CSS 修改?

最佳答案

你不能。

1) 选择器,p:before , 不仅仅是一个选择器——伪元素定义了不影响实际选择的功能。 jQuery 应该返回什么,所有 p标签?就这些了$(...)确实——它返回一堆与您的选择器匹配的元素。 jQuery (Sizzle/querySelectorAll ) 不知道如何获取 :before ...

2) 伪元素/类行为也不能通过 JS API 获得。

通过 JS 动态执行此类操作的唯一方法是创建一个 <style>元素,像这样:

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

请问您当初为什么要这样做?

关于jquery - 使用 `.css` 作为伪元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7731837/

相关文章:

javascript - 未捕获的类型错误 : Cannot read property 'focus' of undefined

toggleclass - 如何在单击时切换多个 div

css - 做 `div::after {content: ""; 高度 : 100% }` only works when ` div {position: absolute;}`?

html - 如何在我的 CSS 中使用来自 fontello 的图标?

css - ie8 "content: attr(foo);"行为怪异

javascript - 为什么这个 'scroll to top' 按钮代码不起作用?

javascript - 从多个 HTML 元素获取值

html - 反转 CSS 属性以更改为 RTL

CSS 布局 : margins and padding versus absolute positioning?

image - 过滤 css 属性在 chrome 中不起作用