使用jQuery修改 :after 伪元素的CSS

5
我使用:after伪元素在方块(<li>)后面显示一个装饰(三角形)。这个想法是区分当前选定的li和其他li这里有示例代码 以下是HTML代码:
<ul>
    <li class="active" style="background-color: hsl(108, 60%, 50%)">One</li>
    <li style="background-color: hsl(36, 60%, 50%)">Two</li>
    <li style="background-color: hsl(252, 60%, 50%)">Three<li>
</ul>

以及 CSS:

ul li {
    width: 300px;
    height: 30px;
    border: 1px dashed;
    position: relative;
}

li.active::after {
    content: " 0020";
    display: block;
    font-size: 0px;
    position: absolute;
    left:100%;
    top: 0%;
    width: 0px;
    height: 0px;
    background: transparent;
    border: 17px solid transparent;
    border-left-color: #FF3900;
}

我希望改变li.active::after伪元素的border-left-color样式属性,使其与具有class=active<li>元素的background-color匹配。
我想到了以下的jquery代码:
$("ul li").click(function() {
    $("ul li").removeClass("active");
    $(this).addClass("active");
    $("li.active::after").css('border-left-color', $(this).css('background-color'));
});

这个没有按预期工作。非常感谢您的帮助。


我不确定这是否是一种复制粘贴或重写错误,但你的 li.active::active 缺少开头和结尾的 " - Albzi
JQuery无法操作:after伪元素,因为伪元素不会出现在DOM中。 - Richard Peck
@BeatAlex 感谢你指出这个错误。这是一个笔误。然而,这并没有解决我的问题。 - Code Poet
2个回答

3
你无法使用jQuery选择伪元素,例如:before和:after。但在你的情况下,你可以通过一个变通方法,在:after上使用父级li的样式,从而匹配border-color属性。
CSS已更新: codepen
ul li {
    width: 300px;
    height: 30px;
    border: 1px dashed;
    position: relative;
}
li:first-of-type.active {
  border-left-color: green; // your exact colors here
}
li:nth-of-type(2).active {
  border-left-color: orange;
}
li:last-of-type.active {
  border-left-color: purple;
}
li.active::after {
    content: " 0020";
    display: block;
    font-size: 0px;
    position: absolute;
    left:100%;
    top: 0%;
    width: 0px;
    height: 0px;
    background: transparent;
    border: 17px solid transparent;
    border-left-color: inherit;
}

然后只需删除包含: after选择器的js行即可。不再需要。


非常聪明。我稍微修改了一下,以便在这里得到我想要的:http://jsfiddle.net/GR2w5/。向你致敬 :) - Code Poet

3
我已经在@DMTinter提交答案时写了这个,所以抱歉会有重复的内容:

使用父元素的边框颜色属性

因为你无法选择JQuery中的伪元素:after:before(对不起,我找不到参考资料),你必须调整父元素的CSS来使其正常工作:

http://jsfiddle.net/kbpg6/2/

根据您的代码:

<ul>
    <li class="active" style="background-color: hsl(108, 60%, 50%); border-color: hsl(108, 60%, 50%)">One</li>
    <li style="background-color: hsl(36, 60%, 50%); border-color: hsl(36, 60%, 50%)">Two</li>
    <li style="background-color: hsl(252, 60%, 50%); border-color: hsl(252, 60%, 50%)">Three<li>
</ul>

ul li {
    width: 300px;
    height: 30px;
    border: 1px dashed;
    position: relative;
    border-color: #ccc; /* -> default "arrow" colour */
}

li.active:after {
    content: " 0020";
    display: block;
    font-size: 0px;
    position: absolute;
    left:100%;
    top: 0%;
    width: 0px;
    height: 0px;
    background: transparent;
    border: 16px solid transparent;
    border-left-color: inherit;
}

抱歉,我必须将它交给@DMTintner,因为我先看到了他的答案。不过还是谢谢你的时间。 - Code Poet
没问题!我从中学到了一些东西,所以没什么大不了的。 - Richard Peck

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