CSS 悬停图像动画兄弟元素

标签 css

我想将鼠标悬停在图像上以使用 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 上时触发动画效果

https://plnkr.co/edit/4qbwdGkW9l5P6WvvtTsP?p=preview

最佳答案

这是因为您有 .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/

相关文章:

javascript - 模式元素垂直对齐不响应任何 CSS,不知道它可能是什么?

javascript - 将功能应用于当前点击并删除其他点击的功能

html - 当我在表单标签中放置一个类属性时,我的 'style.css' 文件不起作用

jquery - Bootstrap Gallery 空白区域

css - 无法使用 css 将静态文件(图像)设置为背景

html - 移动设备扭曲了我网站上的页面

jquery - 在所有标签上应用占位符?

javascript - 如何暂停一个css动画,然后从暂停点继续运行?

javascript - 对齐文本以支持动态内容

JavaScript - onmouseover 修改前一个元素的 css 高度