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

Cod*_*oet 5 css jquery

我使用:after伪元素在一个块(<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>
Run Code Online (Sandbox Code Playgroud)

和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;
}
Run Code Online (Sandbox Code Playgroud)

我想更改伪元素的border-left-color样式属性,li.active::afterbackground-color<li>元素与匹配class=active

我想出了以下jQuery:

$("ul li").click(function() {
    $("ul li").removeClass("active");
    $(this).addClass("active");
    $("li.active::after").css('border-left-color', $(this).css('background-color'));
});
Run Code Online (Sandbox Code Playgroud)

这不符合预期。任何帮助表示赞赏。

DMT*_*ner 3

你不能使用 jquery 选择伪元素,例如 :before 和 :after 。但在您的情况下,您可以采取解决方法,在 :after 上使用父 li 的样式,从而匹配 border-color 属性

代码笔

CSS 更新:

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;
}
Run Code Online (Sandbox Code Playgroud)

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