首页 > 解决方案 > 更改父级的样式:通过悬停子级之后

问题描述

可以说我有这个清单

<ul class="parent">
    ::before
    <li class="child"></li>
    <li class="anotherchild"></li>
    ::after
</ul>

是否可以使用 css、jquery 或 vanilla js更改parent::afteron的样式?child:hover

.child:hover .parent:after{}

似乎不起作用

.parent:hover:after{}

有效,但这不是我希望实现的。

在阅读了几篇文章之后,在 js 中更改伪元素样式似乎很棘手,而且我不确定是否可以将鼠标悬停来更改父级(?)

标签: javascriptjquerycsshtml-lists

解决方案


你不能用纯 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>


推荐阅读