javascript - 更改父级的样式:通过悬停子级之后
问题描述
可以说我有这个清单
<ul class="parent">
::before
<li class="child"></li>
<li class="anotherchild"></li>
::after
</ul>
是否可以使用 css、jquery 或 vanilla js更改parent::after
on的样式?child:hover
.child:hover .parent:after{}
似乎不起作用
.parent:hover:after{}
有效,但这不是我希望实现的。
在阅读了几篇文章之后,在 js 中更改伪元素样式似乎很棘手,而且我不确定是否可以将鼠标悬停来更改父级(?)
解决方案
你不能用纯 css 来做,但你可以用 javascript 或 jQuery 来做。
这是使用 jquery 完成的演示:
$(document).ready(function() {
$(".child").mouseenter(function() {
$(this).parent().addClass("childHovered");
}).mouseleave(function() {
$(this).parent().removeClass("childHovered");
})
})
如果要更改:after
伪元素,则可以将伪效果添加到其他类,如下例所示,我更改了文本颜色
演示
$(document).ready(function() {
$(".child").mouseenter(function() {
$(this).parent().addClass("childHovered");
}).mouseleave(function() {
$(this).parent().removeClass("childHovered");
})
})
.parent.childHovered {
color: blue;
}
.parent.childHovered::after {
content:"";
height:20px;
width:20px;
background-color:#000;
position:absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="parent">
<li class="child">child</li>
<li class="anotherchild">anotherchild</li>
</ul>
推荐阅读
- database - 在一张桌子上放两种饮料是不是一个糟糕的设计?
- sql-update - dolphindb 中的条件前向填充
- gitlab - 在 Gitlab CI 中创建我的软件的两个版本
- flutter - 在杀死或销毁应用程序后,Flutter Localization 不稳定
- javascript - 承诺过早解决
- mysql - 如何在查询中显示多个结果
- mongodb - 使用 golang 和 mongo 查询名字和姓氏
- ldap - OpenLDAP - 如何授予写访问权限但不修改或删除?有什么选择吗?
- mysql - 从 WordPress 数据库中删除特定的 meta_keys
- android - 有没有办法在 JavaFX 和 android 中将 HTML 转换为图像,从而动态地找到图像相对于 HTML 的高度?