访问 css “:after"带有 jQ​​uery 的选择器

2022-01-30 00:00:00 jquery css jquery-selectors

我有以下css:

.pageMenu .active::after {
    content: '';
    margin-top: -6px;
    display: inline-block;
    width: 0px;
    height: 0px;
    border-top: 14px solid white;
    border-left: 14px solid transparent;
    border-bottom: 14px solid white;
    position: absolute;
    right: 0;
}

我想使用 jQuery 更改顶部、左侧和底部边框的边框宽度.我用什么选择器来访问这个元素?我尝试了以下方法,但它似乎不起作用.

I'd like to change the border-width of the top, left, and bottom border using jQuery. What selector to I use to access this element? I tried the following but it doesn't seem to be working.

$('.pageMenu .active:after').css(
        {
            'border-top-width': '22px',
            'border-left-width': '22px',
            'border-right-width': '22px'
        }
    )

推荐答案

你不能操作 :after,因为它在技术上不是 DOM 的一部分,因此任何 JavaScript 都无法访问.但是您可以添加一个新的类并指定一个新的 :after.

You can't manipulate :after, because it's not technically part of the DOM and therefore is inaccessible by any JavaScript. But you can add a new class with a new :after specified.

CSS:

.pageMenu .active.changed:after { 
/* this selector is more specific, so it takes precedence over the other :after */
    border-top-width: 22px;
    border-left-width: 22px;
    border-right-width: 22px;
}

JS:

$('.pageMenu .active').toggleClass('changed');

<小时>

更新:虽然不可能直接修改 :after 内容,但有一些方法可以使用 JavaScript 读取和/或覆盖它.请参阅使用 jQuery 操作 CSS 伪元素(例如 :before 和 :after)"完整的技术列表.


UPDATE: while it's impossible to directly modify the :after content, there are ways to read and/or override it using JavaScript. See "Manipulating CSS pseudo-elements using jQuery (e.g. :before and :after)" for a comprehensive list of techniques.

相关文章