使用jQuery获取CSS的内容

Mic*_*elS 9 css jquery

我有以下CSS

h1:before {
    content: "Chapter " counter(lvl1) "\000d\000a";
    counter-increment: lvl1;
    white-space: pre-wrap;
}
h1 {
    page-break-before: right;
}
Run Code Online (Sandbox Code Playgroud)

和这个HTML

<p>...</p>
<h1>A Title</h1>
<p>...</p>
Run Code Online (Sandbox Code Playgroud)

使用给定的CSS,我得到类似的东西

Chapter 1
A Title
Run Code Online (Sandbox Code Playgroud)

当我尝试使用jQuery获取文本时,我得到"A Title".是否有可能获得"第1章\n标题"?

谢谢

Dav*_*mas 27

用途getComputedStyle():

$('h1').each(function(){
    console.log(window.getComputedStyle(this,':before').content);
});
Run Code Online (Sandbox Code Playgroud)

before()是用于遍历DOM一个jQuery方法,它获取/设置前述元件,它并访问伪元素.

工作JS Fiddle,由Eric提供.

虽然有一个不幸的警告,这种方法返回声明中使用的文字字符串content,而不是实际生成的内容.

  • 实际上,这并不完全正确,因为它从 CSS 文件中获取文字`:before` 内容,而不是实际生成的内容。OP 想要`Chapter 1`,而不是`Chapter " counter(lvl1)`...很酷的答案,但我认为在这种情况下它没有用。 (2认同)