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

dmr*_*dmr 207 css jquery 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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

Bla*_*ger 268

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

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

JS:

$('.pageMenu .active').toggleClass('changed');
Run Code Online (Sandbox Code Playgroud)

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

  • @Kamlesh你可以使用这个链接代替... https://web.archive.org/web/20170715014139/https://pankajparashar.com/posts/modify-pseudo-elements-css/ (2认同)

小智 55

您可以类似的html代码之后添加样式:
例如:

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

  • 在jQuery中:`$("<style> .wrapper:after {border-top-width:"+ value +"px;} </ style>").appendTo("head")` (7认同)
  • 这对于动态属性很有用。谢谢! (2认同)

小智 7

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

$('.active').after().click(function () {
    alert('clickable!');
});
Run Code Online (Sandbox Code Playgroud)

请参阅jQuery文档.

  • 这不起作用,但好主意 (9认同)
  • 您指向 jQuery 文档的链接说明您的回复是错误的 (4认同)
  • 这对我在 Firefox、Chrome 和 Safari 中有效 (3认同)
  • 不适用于CSS,但让我在:after标签上定位click事件 (2认同)
  • jquery之后并不意味着操纵":after"css属性,而是元素本身. (2认同)