悬停一个元素时如何影响其他元素

HTML CSS

伽罗Tony小卤蛋

2020-03-18

我想做的是将某个div对象悬停时,它会影响另一个对象的属性div

例如,在这个JSFiddle演示中,当您将鼠标悬停在#cube其上时,它会发生变化,background-color但是我想要的是,当我将鼠标悬停在上时#container#cube它会受到影响。

div {
  outline: 1px solid red;
}
#container {
  width: 200px;
  height: 30px;
}
#cube {
  width: 30px;
  height: 100%;
  background-color: red;
}
#cube:hover {
  width: 30px;
  height: 100%;
  background-color: blue;
}
<div id="container">

  <div id="cube">
  </div>

</div>

第2196篇《悬停一个元素时如何影响其他元素》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
古一梅 2020.03.18

这是另一个想法,您可以在不考虑任何特定选择器的情况下,仅通过使用:hover主元素状态来影响其他元素

为此,我将依靠自定义属性(CSS变量)的使用。正如我们在规范中所读到的

自定义属性是普通属性,因此可以在任何元素上声明它们,并使用常规继承级联 规则进行解析...

这个想法是在主元素内定义自定义属性,并使用它们来设置子元素的样式,由于这些属性是继承的,因此我们只需要在悬停时在主元素内更改它们即可。

这是一个例子:

#container {
  width: 200px;
  height: 30px;
  border: 1px solid var(--c);
  --c:red;
}
#container:hover {
  --c:blue;
}
#container > div {
  width: 30px;
  height: 100%;
  background-color: var(--c);
}
<div id="container">
  <div>
  </div>
</div>

为什么这会比结合使用特定选择器和悬停更好?

我可以提供至少2个使这种方法成为值得考虑的理由:

  1. 如果我们有许多嵌套的元素共享相同的样式,这将避免我们使用复杂的选择器将所有这些元素作为目标悬停。使用自定义属性,我们只需将鼠标悬停在父元素上即可更改该值。
  2. A custom property can be used to replace a value of any property and also a partial value of it. For example we can define a custom property for a color and we use it within a border, linear-gradient, background-color, box-shadow etc. This will avoid us reseting all these properties on hover.

Here is a more complex example:

.container {
  --c:red;
  width:400px;
  display:flex;
  border:1px solid var(--c);
  justify-content:space-between;
  padding:5px;
  background:linear-gradient(var(--c),var(--c)) 0 50%/100% 3px no-repeat;
}
.box {
  width:30%;
  background:var(--c);
  box-shadow:0px 0px 5px var(--c);
  position:relative;
}
.box:before {
  content:"A";
  display:block;
  width:15px;
  margin:0 auto;
  height:100%;
  color:var(--c);
  background:#fff;
}

/*Hover*/
.container:hover {
  --c:blue;
}
<div class="container">
<div class="box"></div>
<div class="box"></div>
</div>

As we can see above, we only need one CSS declaration in order to change many properties of different elements.

理查德A小宇宙 2020.03.18

只有这对我有用:

#container:hover .cube { background-color: yellow; }

.cube的CssClass 在哪里#cube

FirefoxChromeEdge中进行了测试

泡芙樱 2020.03.18

在此特定示例中,您可以使用:

#container:hover #cube {
    background-color: yellow;   
}

此示例仅适用于,因为它cube是的子级container对于更复杂的场景,您需要使用其他CSS或JavaScript。

小小仲羽 2020.03.18

如果多维数据集直接位于容器内部:

#container:hover > #cube { background-color: yellow; }

如果多维数据集位于容器旁边(在容器关闭标签之后):

#container:hover + #cube { background-color: yellow; }

如果多维数据集在容器内的某个位置:

#container:hover #cube { background-color: yellow; }

如果多维数据集是容器的同级:

#container:hover ~ #cube { background-color: yellow; }

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android