【问题标题】:Insert text over an image and change the text by hovering the mouse over (JavaScript)在图像上插入文本并通过将鼠标悬停在 (JavaScript) 上来更改文本
【发布时间】:2021-06-28 09:22:26
【问题描述】:
我有这个 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
mouseover
onmouseover
mouseout
onmouseout
【解决方案1】:
对于这样的作业,您不需要 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,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>