如何使用jQuery访问伪元素的样式属性?

15

为了更好的理解,这是对早前问题的跟进。与其深入挖掘cssRules,我想基于jQuery选择器搜索这些规则的效果来构建逻辑。

假设默认属性为

.commentarea .author:before {
    background-image: url(http://...);
    background-position: -9999px -9999px;
    /* ... */
}

像选择性地修改那样

.author[href$="gbacon"]:before /* ... */ {
  content: "";
  background-position: 0 -140px
}

如何选择具有默认背景位置的伪元素?像这样复制选择器:

GM_log("size = " + $(".commentarea .author:before").size());

没有匹配项。尝试使用.siblings()方法。

$(".commentarea .author")
  .map(function(i) {
         GM_log($(this)
                  .siblings()
                  .map(function (i) { return $(this).css("background-image") })
                  .get()
                  .join(", "))
       });

只生成none值。

完整的信息请参见实时页面。这个可能吗?


所以基本上您想选择.class1 .class2,只要元素的背景图像和位置是默认的(基于CSS规则)? - Chris Laplante
你能贴出你正在处理的HTML代码片段吗? - Chris Laplante
@SimpleCoder 我想选择.class1 .class2,只要相邻的伪元素的背景位置是默认的。 - Greg Bacon
@Greg Bacon:不过我仍然可以提供一个解决方案。你所说的邻近,是指任何方向吗? - Chris Laplante
@joberror 请查看实时页面 - Greg Bacon
显示剩余2条评论
1个回答

6
您不能像这样使用:before:after伪元素。它们的目的是在您指定的选择器前面和后面(分别)插入内容。 示例用法: HTML:
<span class='a'>
    Outer
    <span class='b'>
        Inner
    </span>
</span>

CSS:

.a .b:before {
    content: "|Inserted using :before|";
}

.a {
    color: blue;
}

.b {
    color: red;
}

结果:

http://jsfiddle.net/mzcp6/

发生的情况是,文本|Inserted using :before|被插入到内部span之前(实际上是在其前面插入了)因为它是classb并且是class a元素的后代。基本上,:before:after并不是选择器,而是修改器。

例子:

这个例子不能按预期工作:

HTML:

<span class='a'>
    <p>More text</p>
    <span class='b'>
        <p>More text</p>
        Inner
    </span>
</span>

CSS:

.a .b:before {
    text-size: 100px;
}

什么都不会发生:

http://jsfiddle.net/bQ2ty/

编辑:

:before 不是有效的 jQuery 选择器: http://api.jquery.com/category/selectors/

我认为你需要使用其他东西,而不是 :before,或者尝试使用 jQuery 插件提取原始规则: http://flesler.blogspot.com/2007/11/jqueryrule.html


7
我认为值得注意的是,由 :before:after 生成的内容实际上不会显示在 DOM 中(因为它们纯粹是呈现性的),因此,没有办法使用 jQuery 选择它们。 - Yi Jiang
@Yi Jiang - 没错,我也注意到了,但是没有提及。谢谢。 - Chris Laplante

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接