如何使用 javascript 或 jquery 修改 :before psedo-element 属性?
我正在尝试修改伪元素 :before
的“left”属性。我使用 JavaScript 或 jQuery 修改任何其他元素都没有问题,但在尝试修改 :before
选项卡中的元素时似乎陷入困境。
举例来说,我似乎无法将下面 :before
元素的 left
属性设置为 200
。
我的 css:
#buttonBox {
position: absolute;
width:150px;
z-index:10;
left:298px;
top: 130px;
}
#buttonBox:before {
position: absolute;
content: "";
top: -8px;
left: 80px;
margin-left: -8px;
border-bottom: 8px solid #ddd;
border-left: 8px solid transparent;
border-right: 8px solid transparent;
border-top: 0;
border-bottom-color: #1e2227;
}
在 javascript 中:
document.getElementById("#buttonBox:before")
产生 null
,因此无法进行设置。
jQuery:
$("#buttonBox:before").offset({top: -8, left: 200});
在设置 left
属性时同样没有响应。
关于如何修改伪元素的属性,我缺少什么吗?我在谷歌上搜索这个没有任何运气。
I am trying to modify the "left" attribute of a pseudo-element :before
. I am having no trouble modifying any other elements using either JavaScript or jQuery, but seem to be stuck when trying to modify an element in the :before
tab.
By way of example, I cant seem to set the left
attribute of the :before
element below to 200
.
My css:
#buttonBox {
position: absolute;
width:150px;
z-index:10;
left:298px;
top: 130px;
}
#buttonBox:before {
position: absolute;
content: "";
top: -8px;
left: 80px;
margin-left: -8px;
border-bottom: 8px solid #ddd;
border-left: 8px solid transparent;
border-right: 8px solid transparent;
border-top: 0;
border-bottom-color: #1e2227;
}
In javascript:
document.getElementById("#buttonBox:before")
yields null
, making it impossible to set that.
jQuery:
$("#buttonBox:before").offset({top: -8, left: 200});
is similarly unresponsive in setting the left
attribute.
Is there something I am missing on how to modify attributes of pseudo-elements? I'm not having any luck Googling this one.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法使用 JQuery 修改伪元素。使用类来操作它们的 CSS 属性。示例:
必要时将通过 Javascript 应用
.active
类。You can't modify pseudo-elements with JQuery. Use classes to manipulate their CSS attributes instead. Example:
The
.active
class would be applied via Javascript when necessary.您可以通过JS修改
:before
和:after
,但这很烦人,您可能不应该这么做。为此,您需要使用相同的选择器,并手动将新的
style
元素添加到包含新样式的网页的head
中:伪元素是实际上是 DOM 元素(因此是“伪”)。除了添加/删除样式表之外,它们不以 JavaScript 可以访问的方式存在。
You can modify
:before
and:after
via JS, but it's annoying enough that you probably shouldn't.To do it, you'd need to use an identical selector and manually add a new
style
element to thehead
of the webpage containing the new styles:Pseudo-elements aren't actually DOM elements (hence the "pseudo"). They don't exist in a way that JavaScript can access beyond adding/removing stylesheets.
也许你可以使用 jQuery 中的 prev() 函数?
http://api.jquery.com/prev/
Maybe you could use the prev() function in jQuery?
http://api.jquery.com/prev/