使用 jQuery 访问 css ":after" 选择器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17788990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:58:46  来源:igfitidea点击:

Access the css ":after" selector with jQuery

jquerycssjquery-selectors

提问by dmr

I have the following css:

我有以下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;
}

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.

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

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

回答by Blazemonger

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

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

CSS:

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:

JS:

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


UPDATE:while it's impossible to directlymodify the :aftercontent, 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.

更新:虽然无法直接修改:after内容,但可以使用 JavaScript 读取和/或覆盖它。请参阅“使用 jQuery 操作 CSS 伪元素(例如 :before 和 :after)”以获得完整的技术列表。

回答by r0mank

You can add style for :aftera like html code.
For example:

您可以为:after类似的 html 代码添加样式。
例如:

var value = 22;
body.append('<style>.wrapper:after{border-top-width: ' + value + 'px;}</style>');

回答by unpezvivo

If you use jQuery built-in after()with empty value it will create a dynamic object that will match your :afterCSS selector.

如果您使用after()带有空值的内置 jQuery ,它将创建一个与您的:afterCSS 选择器匹配的动态对象。

$('.active').after().click(function () {
    alert('clickable!');
});

See the jQuery documentation.

请参阅jQuery 文档