使用jQuery修改:after伪元素的CSS [英] Modify CSS of the :after pseudo-element using jQuery

查看:2312
本文介绍了使用jQuery修改:after伪元素的CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用:after伪元素在一个块(本例中为<li>)之后显示一个装饰(三角形).这个想法是要区分当前选择的li与其他.

I use the :after pseudo-element to display a decoration (triangle) after a block (<li> in my case). The idea is to distinguish the currently selected li from others.

在此处拨弄

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样式属性,以将<li>元素的background-colorclass=active匹配.

I want to change the border-left-color style attribute of li.active::after pseudo element to match the background-color of the <li> element with class=active.

我想到了以下jquery:

I came up with the following jquery:

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

这不符合预期.感谢您的帮助.

This doesn't work as expected. Any help is appreciated.

推荐答案

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

you can't select pseudo elements such as :before and :after with jquery. But in your case you can do a workaround to use the parent li's style on the :after and thus match the border-color property

codepen

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;
}

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

and then just remove the line of js that includes the :after selector. not needed anymore

这篇关于使用jQuery修改:after伪元素的CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆