在图像标签内显示文本。

3

如果我有<img src='Assets/image.png'>一些文本</img>,是否可能使“一些文本”显示出来?

我知道我可以使用div并将其样式设置为在图像上方显示,但我想知道的是是否有任何方法可以使标签内的文本显示出来。


据我所知,你不能这样做。 - Jesse
1个回答

6

不行。img标签内没有文本。根据规范,img元素是一个空元素,即它没有任何内容或结束标记。

好消息是,在您的示例源代码中,“some text”文本将显示在页面上。(从技术上讲,它不在img标签内,因此直接显示在其后面。)但这可能不是您想要的...

可能的解决方案有:

  • If you want a text that is displayed instead of the image whenever the image cannot be displayed, put the text inside the alt attribute.
  • For a text that is shown when the user hovers the mouse over the image, use the title attribute
  • To display both the image and the text in the page, use a figure element in which you put the img and put the text inside the figcaption and use CSS positioning to put the figcaption on top of the image.
    figure {
      position: relative
    }
    figcaption {
      position: absolute;
      width: 200px;
      line-height: 150px;
      text-align: center;
      left: 0;
      top: 0;
      text-shadow: 0 0 1px white;
      font-weight:bold;
    }
    <figure>
      <img src="http://lorempixel.com/200/150" />
      <figcaption>some text</figcaption>
    </figure>

好的,谢谢!我认为为了实现我想做的事情,我需要稍微不同的方法。 - Csteele5
好的。我编辑了答案并添加了一个实际的解决方案。希望能有所帮助! - Mr Lister

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接