通过将鼠标悬停在 parent:after 上更改样式

Change styling on parent:after by hovering child

假设我有这个列表

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

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

.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 伪元素,那么你可以将伪效果添加到其他 class 就像下面我更改文本颜色的示例

演示

$(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>

Javascript 解决方案


向样式表添加规则

const child = document.querySelector(".child");

child.addEventListener("mouseenter", () => {
  const parent = child.parentElement;
  document.styleSheets[0].addRule('div.parent:after', 'content: "Hovering";');
})

child.addEventListener("mouseleave", () => {
  const parent = child.parentElement;
  document.styleSheets[0].addRule('div.parent:after', 'content: "Not Hovering";');
})
.parent::after {
  content: "Not Hovering";
}
<div class="parent">
  <button class="child">Child</button>
</div>


解决方案使用 类

const child = document.querySelector(".child");

child.addEventListener("mouseenter", () => {
  child.parentElement.classList.toggle("hovering");
  
})

child.addEventListener("mouseleave", () => {
  child.parentElement.classList.toggle("hovering");
})
.parent::after {
  content: "Not Hovering";
}

.parent.hovering::after {
  content: "Hovering";
}
<div class="parent">
  <button class="child">Child</button>
</div>