【问题标题】:Access the css ":after" selector with jQuery [duplicate]使用 jQuery 访问 css ":after" 选择器 [重复]
【发布时间】:2017-08-23 13:31:44
【问题描述】:

我有以下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 更改顶部、左侧和底部边框的边框宽度。我用什么选择器来访问这个元素?我尝试了以下方法,但似乎不起作用。

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

【问题讨论】:

标签: jquery css jquery-selectors


【解决方案1】:

您不能操作: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;
}

JS:

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

更新:虽然无法直接修改 :after 内容,但有一些方法可以使用 JavaScript 读取和/或覆盖它。有关技术的完整列表,请参阅 "Manipulating CSS pseudo-elements using jQuery (e.g. :before and :after)"

【讨论】:

【解决方案2】:

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

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

【讨论】:

  • 这对于动态属性很有用。谢谢!
  • 在 jQuery 中:$( "&lt;style&gt;.wrapper:after { border-top-width: " + value + "px; }&lt;/style&gt;" ).appendTo( "head" )
【解决方案3】:

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

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

请参阅jQuery documentation

【讨论】:

  • 这行不通,不过是个好主意
  • 这适用于我在 Firefox、Chrome 和 Safari 中
  • 不适用于 CSS,但让我可以在 :after 标签上定位点击事件
  • jquery after 并不是要操纵 ":after" css 属性,而是要操纵元素本身。
  • 您的 jQuery 文档链接说明您的回答是错误的
猜你喜欢
  • 2021-07-31
  • 2011-08-17
  • 2012-02-28
相关资源
最近更新 更多