【问题标题】:CSS make a hover affect other items [duplicate]CSS使悬停影响其他项目[重复]
【发布时间】:2022-10-30 08:47:51
【问题描述】:

当我将鼠标悬停在图像上时,我希望#parent div 中的所有内容都改变宽度,但我的光标所在的图像不会改变。

换句话说,是否有 CSS Parent 选择器?

这是我现在不起作用的代码:

img {
  width: 340px
}

body {
  background-color: black;
}

img:hover~#parent {
  width: 34px
}
<body>
  <div id="parent">
    <img src="https://www.tazzadesign.com/wp-content/uploads/sites/65/2013/11/dummy-image-square.jpg">
    <img src="https://www.tazzadesign.com/wp-content/uploads/sites/65/2013/11/dummy-image-square.jpg">
    <img src="https://www.tazzadesign.com/wp-content/uploads/sites/65/2013/11/dummy-image-square.jpg">
  </div>
</body>

【问题讨论】:

  • 没有理由将我们发送到另一个站点。请查看How to Ask 并使用帖子编辑器创建live demo

标签: html css


【解决方案1】:

链接的可能重复项可能对您有一个很好的答案,但是这个问题也可以用 js 解决,也可以使用 mouseover / mouseout 事件。

const parent = document.querySelector(".parent");
const children = [...document.querySelectorAll(".child")];
children.forEach(child => {
  child.addEventListener(
    "mouseover", 
    () => parent.classList.add("child-hover")
  );
  child.addEventListener(
    "mouseout", 
    () => parent.classList.remove("child-hover")
  );
});
.parent {
  position: absolute;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: space-around;

  --b-color: blue;
  border: 5px solid var(--b-color);
  
  transition: 0.1s;
}

.parent.child-hover {
  --b-color: green;
}

.child {
  --size: 10rem;
  height: var(--size);
  width: var(--size);
  --b-color: gray;
  border: 5px solid var(--b-color);
  
  transition: 0.1s;
}

.parent.child-hover .child {
  transform: scale(0.1);
}

.parent.child-hover .child:hover {
  transform: scale(1);
}

.child:hover {
  --b-color: lightgreen;
}
<div class="parent">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>

【讨论】:

    【解决方案2】:

    您正在尝试选择一个无效的父元素。 CSS 不会那样做。然后,波浪号运算符 (~) 是随后的兄弟组合选择器 (docs)。只会影响兄弟姐妹活跃的。

    有关可能的解决方案,请参阅链接的副本。

    img {
      width: 340px
    }
    
    body {
      background-color: black;
    }
    
    img:hover~img {
      width: 34px
    }
    <body>
      <div id="parent">
        <img src="https://www.tazzadesign.com/wp-content/uploads/sites/65/2013/11/dummy-image-square.jpg">
        <img src="https://www.tazzadesign.com/wp-content/uploads/sites/65/2013/11/dummy-image-square.jpg">
        <img src="https://www.tazzadesign.com/wp-content/uploads/sites/65/2013/11/dummy-image-square.jpg">
      </div>
    </body>

    【讨论】:

      猜你喜欢
      • 2015-04-20
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 2013-08-01
      • 1970-01-01
      • 2020-07-04
      • 1970-01-01
      • 2015-07-31
      相关资源
      最近更新 更多