在图像上插入文本并通过将鼠标悬停在 (JavaScript) 上来更改文本

问题描述

我有这个 HTML 代码,我想在它的中心为这个图像插入一个描述性文本。之后,我想通过将鼠标悬停在图像上来更改文本。对此有什么想法吗?我尝试了几种解决方案,但大多数都没有针对多张图片做到这一点,尤其是针对一张图片。

<div class="col-4 col-6-medium col-12-small">
    <a href="#" class="image fit">
        <img src="images/pic01.jpg" alt="">
    </a>
</div>

解决方法

对于这样的任务,你不需要 javascript

让浏览器为你做#pureCss

(使用 javascript 来操作 DOM 或更改 div 上的类是不必要的)

您可以添加任何具有更高性能的动画(使用 css)

.image.fit{
  /* block capabilities,but still next to each other */  
  display: inline-block;
  /* be the parent for position absolute later */
  position: relative;
}

.image.fit .normal,.image.fit .hover {
  /* position of the box */
  position: absolute;
  bottom: 5%;
  left: 5%;
  right: 5%;

  /* nice box with padding even for multiline */
  background-color: rgba(255,255,0.6);
  padding: 5%;
  text-align: center;
  font-family: Arial;
  color: #333;

  /* animate fade,rather than blinking */
  transition: opacity 0.5s;
}

.image.fit .normal {
  opacity: 1; /* visible by default */
}
.image.fit:hover .normal {
  opacity: 0; /* not visible on hover */
}

.image.fit .hover {
  opacity: 0; /* not visible by default */

  /* optional position on top (remove,for the same place) */
  top: 5%;   
  bottom: auto;
}
.image.fit:hover .hover {
  opacity: 1; /* visible on hover */
}
<div class="col-4 col-6-medium col-12-small">
    <a href="#" class="image fit">
        <img src="https://picsum.photos/id/1015/300/150" alt="">
        <div class="normal">water</div>
        <div class="hover">you can go tomorrow,tickets available</div>
    </a>
    <a href="#" class="image fit">
        <img src="https://picsum.photos/id/1016/300/150" alt="">
        <div class="normal">rocks</div>
        <div class="hover">Lorem Ipsum: Neque porro quisquam est qui dolorem ipsum quia dolor sit amet,consectetur,adipisci velit...</div>
    </a>

</div>

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...