<分区>
<分区>
我正在尝试使用 HTML 和 CSS 将鼠标悬停在第 3 个 div 上时,转换 2 个单独 div 中 2 个背景图像的不透明度。看起来相当直截了当,但我没有运气搜索悬停目标上的所有内容,包括 not:hover、parents siblings 等。这是我的代码笔示例的链接。我的目标是通过仅悬停框 3(蓝色框)并在悬停时恢复来影响框 1 和 2 的不透明度。欢迎所有关于重组和/或样式的建议。谢谢。
https://codepen.io/NikoVanDam/pen/Ygzjpz
HTML
<body>
<div class="Container">
<div class="Box1"></div>
<div class="Filler1"></div>
<div class="Box2"></div>
<div class="Filler2"></div>
<div class="Box3"></div>
</div>
</body>
CSS
.Container {
width: 383px;
height: 404px;
background: yellow;
float: left;
}
.Box1 {
width: 383px;
height: 210px;
background: red;
float: left;
opacity: 0.2;
transition: opacity 0.5s ease-in-out;
-webkit-transition: opacity 0.5s ease-in-out;
-moz-transition: opacity 0.5s ease-in-out;
-ms-transition: opacity 0.5s ease-in-out;
}
.Filler1 {
width: 130px;
height: 194px;
background: grey;
float: left;
}
.Box2 {
width: 253px;
height: 110px;
background: blue;
float: left;
Opacity: 0.2;
transition: opacity 0.5s ease-in-out;
-webkit-transition: opacity 0.5s ease-in-out;
-moz-transition: opacity 0.5s ease-in-out;
-ms-transition: opacity 0.5s ease-in-out;
}
.Filler2 {
width: 160px;
height: 84px;
background: grey;
float: left;
}
.Box3 {
width: 93px;
height: 84px;
background: blue;
float: left;
}
最佳答案
不幸的是,没有纯 CSS 方法来完成此操作,因为 .Box3:hover
位于您希望定位的元素之后。这是一个简单的 JavaScript 方法作为安慰奖。
const box3 = document.querySelector('.Box3');
const container = document.querySelector('.Container');
box3.addEventListener("mouseover", handleMouseOver);
box3.addEventListener("mouseout", handleMouseOut);
function handleMouseOver() {
container.classList.add('hover');
}
function handleMouseOut() {
container.classList.remove('hover');
}
.Container {
width: 383px;
height: 404px;
background: yellow;
float: left;
}
.Box1 {
width: 383px;
height: 210px;
background: red;
float: left;
opacity: 0.2;
transition: opacity 0.5s ease-in-out;
}
.Filler1 {
width: 130px;
height: 194px;
background: grey;
float: left;
}
.Box2 {
width: 253px;
height: 110px;
background: blue;
float: left;
Opacity: 0.2;
transition: opacity 0.5s ease-in-out;
}
.Filler2 {
width: 160px;
height: 84px;
background: grey;
float: left;
}
.Box3 {
width: 93px;
height: 84px;
background: blue;
float: left;
}
.hover .Box1,
.hover .Box2 {
opacity: .7;
}
<body>
<div class="Container">
<div class="Box1"></div>
<div class="Filler1"></div>
<div class="Box2"></div>
<div class="Filler2"></div>
<div class="Box3"></div>
</div>
</body>
关于html - 将鼠标悬停在第 3 个上时更改 2 个 div 背景图像的不透明度?仅 HTML 和 CSS 还是我需要 JS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54879662/