我想将鼠标悬停在图像上以使用 CSS 动画显示一段文本。问题是我似乎只能为子元素设置动画。
<div id="does-not-work">
<p>DOES NOT WORK</p>
<p>Hover over the image</p>
<img src="https://3.bp.blogspot.com/-W__wiaHUjwI/Vt3Grd8df0I/AAAAAAAAA78/7xqUNj8ujtY/s1600/image02.png"/>
<p class="show-bubble">Should display this text</p>
</div>
#does-not-work img:hover .show-bubble{
max-height: 200px;
}
我的期望是,我将鼠标悬停在 #does-not-work
div 内的 img 元素上,它应该会更改 .show-bubble
的最大高度。但事实并非如此。
虽然使用这样的 html 结构确实有效:
<div id="does-work">
<p>DOES WORK</p>
<p>Hover over the image</p>
<img src="https://3.bp.blogspot.com/-W__wiaHUjwI/Vt3Grd8df0I/AAAAAAAAA78/7xqUNj8ujtY/s1600/image02.png"/>
<p class="show-bubble">Should display this text</p>
</div>
#does-work:hover .show-bubble{
max-height: 200px;
}
这是因为悬停现在位于我要显示的 block 的父元素上。问题是我只想在用户将鼠标悬停在图像上而不是整个 block 上时触发动画效果
最佳答案
这是因为您有 .hover
作为父元素和 img
标签。所以两个悬停同时触发
Remove this code
#does-not-work img:hover .show-bubble{
max-height: 200px;
}
#does-work:hover .show-bubble{
max-height: 200px;
}
And add this code
#does-not-work img:hover ~ .show-bubble{
max-height: 200px;
}
关于CSS 悬停图像动画兄弟元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41484681/