【问题标题】:Get Before-Content of CSS with jQuery使用 jQuery 获取 CSS 的前内容
【发布时间】:2013-02-16 17:47:58
【问题描述】:

我有以下 CSS

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

还有这个 HTML

<p>...</p>
<h1>A Title</h1>
<p>...</p>

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

Chapter 1
A Title

当我尝试使用 jQuery 获取文本时,我得到“A Title”。是否有可能获得“Chapter 1\nA Title”?

谢谢

【问题讨论】:

    标签: jquery css


    【解决方案1】:

    使用getComputedStyle():

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

    before()是一个用于遍历DOM的jQuery方法,它获取/设置前面的元素,它访问伪元素。

    Working JS Fiddle,由Eric提供。

    虽然不幸的是,这种方法返回的是content 声明中使用的literal 字符串,而不是实际 生成的内容。

    【讨论】:

    • 实际上,这并不完全正确,因为它从 CSS 文件中获取文字 :before 内容,而不是实际生成的内容。 OP 想要 Chapter 1,而不是 Chapter " counter(lvl1)... 很酷的答案,但我认为在这种情况下它不会有用。
    • 正如@WesleyMurch 所说,这给了我Chapter " Counter(lvl1) 而不是Chapter 1
    • @MichaelS:确实,我正在努力解决这个问题。不幸的是,我在这样做时遇到了麻烦,所以这可能是不可能的。
    • 任何(简单)选项可以为 IE8 获取此内容?仅 IE11+ 支持带有伪元素的 getComputedStyle developer.mozilla.org/en-US/docs/Web/API/…
    • @retrovertigo:我不知道,不,很遗憾。
    猜你喜欢
    • 2014-03-26
    • 1970-01-01
    • 2015-11-16
    • 2012-02-07
    • 1970-01-01
    • 2011-04-05
    • 2012-03-11
    • 1970-01-01
    相关资源
    最近更新 更多