悬停效果不影响链式 Div

问题描述 投票:0回答:1

问题由一个 div

.hoverbox
的悬停样式链接到另一个 div
.menubox

但是当我将鼠标悬停在

.hoverbox
上时,
.menubox
没有发生任何事情。

这是我的代码:

body {
  display: flex;
  align-items: center;
  justify-content: center;
  background: #000;
  margin: 0;
  width: 100%
}

.flowbox {
  display: block;
  background: #fff;
  aspect-ratio: 1/1;
  height: 90vh;
  border-radius: 5vh;
  z-index: 3;
}

.grid {
  display: grid;
  column-gap: 0;
  grid-template-columns: 25vh 90vh 25vh;
}

.hoverbox {
  display: block;
  border: 2px solid green;
  z-index: 10;
  background-color: #0080FF80;
}

.hoverbox:hover .menubox {
  transform: translateX(-40vh);
  background-color: #ff0000
}

.menubox {
  position: absolute;
  background-color: #e8e8e8;
  aspect-ratio: 1/1;
  height: 90vh;
  z-index: 0;
  transform: translateX(0);
  transition: transform 130ms ease-out;
}
<div class="menubox"></div>

<div class="grid">
  <div class="hoverbox"></div>
  <div class="flowbox"></div>
  <div class="hoverbox"></div>
</div>

我以前用过这个方法,但现在它不起作用了,也许是因为网格的原因?

html css hover
1个回答
0
投票

为此,当您尝试通过将鼠标悬停在后来同级的子元素上来设置元素的样式时,您需要使用

:has()
伪类(尽管请注意兼容性问题,请参阅参考文献):

body {
  display: flex;
  align-items: center;
  justify-content: center;
  background: #000;
  margin: 0;
  width: 100%
}

.flowbox {
  display: block;
  background: #fff;
  aspect-ratio: 1/1;
  height: 90vh;
  border-radius: 5vh;
  z-index: 3;
}

.grid {
  display: grid;
  column-gap: 0;
  grid-template-columns: 25vh 90vh 25vh;
}

.hoverbox {
  display: block;
  border: 2px solid green;
  z-index: 10;
  background-color: #0080FF80;
}

.menubox {
  position: absolute;
  background-color: #e8e8e8;
  aspect-ratio: 1/1;
  height: 90vh;
  z-index: 0;
  transform: translateX(0);
  transition: transform 130ms ease-out;
}

/*
  here we select the .menubox element, when the parent has a descendant
  element of class '.hoverbox' that matches the :hover pseudo-class:
*/
body:has(.hoverbox:hover) .menubox {
  transform: translateX(-40vh);
  background-color: #ff0000;
}
<div class="menubox"></div>

<div class="grid">
  <div class="hoverbox"></div>
  <div class="flowbox"></div>
  <div class="hoverbox"></div>
</div>

JS Fiddle 演示.

参考资料:

© www.soinside.com 2019 - 2024. All rights reserved.