html - 不明白悬停图像时如何显示标题

标签 html css

我在这个例子中遇到了一些困难:

<img src="image1/<?php echo $file; ?>.jpg" style="width:500px" /> 
<p id="caption"><?php echo $caption; ?></p> 

我试图在悬停图像时使用 CSS 获取标题。

我尝试使用 a img{hover;}p {hover;}

有没有办法让我在悬停图像时获得标题?该示例是在 PHP 中,如果它是在 CSS 或 Javascript 中,也许我可以搜索它,但到目前为止我找不到解决方案。

我很感激任何解释和例子。

最佳答案

/* by default, hide caption: */
#caption { display: none; } 
/* if caption is next to a hovered img, show: */
img:hover + #caption { display: block; }

jsFiddle Demo

  • +Adjacent Sibling Selector , 受 IE8 支持。
  • :hover伪类用于设置鼠标经过的元素的样式
  • 请注意,如果您想在文档中使用多个标题,则应使用类而不是 ID。 ID 在文档中必须是唯一的。

如果您需要在 IE7 中工作的东西,请考虑这样的 HTML:

<div class="image-with-caption">
    <img src="whatever.png" style="width:200px" /> 
    <p class="caption">caption</p> 
</div>

CSS 将是:

.caption { display: none; }
.image-with-caption:hover .caption { display: block; }​

jsFiddle Demo

关于html - 不明白悬停图像时如何显示标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11057056/

相关文章:

html - 如何水平对齐 div 元素到另一个 div?

html - 如果对象重叠,带有嵌套 float div 的父级负边距将不会跟随父级

html - CSS背景图片查询

css - 改善 flexbox 行的平衡

javascript - jquery.val() 返回未定义

javascript - 为什么 Chart.js 不显示我的输出(const 函数的结果)?

javascript - polymer 1.0 : Is there any way to use 'layout' as an attribute instead of as a CSS class or using Attribute serialization in the class attribute?

css - 当我添加 &lt;!DOCTYPE html> 时,div 测量不起作用

jquery - 使用 CSS 为 SVG 路径元素的填充设置动画

css - 背景颜色的背景位置