img鼠标悬停显示文字
时间: 2023-08-24 15:04:56 浏览: 161
要实现鼠标悬停图片显示文字的效果,可以使用HTML和CSS的技术来完成。
首先,需要在HTML中将图片和对应的文字包装在一个容器中,比如使用`<div>`标签:
```html
<div class="img-container">
<img src="image.jpg" alt="图片描述">
<div class="text-overlay">文字描述</div>
</div>
```
然后,使用CSS设置容器的样式,包括设置图片宽度、高度、position和z-index等属性,同时将文字的位置设置为绝对定位,并且隐藏文字:
```css
.img-container {
position: relative;
width: 200px;
height: 200px;
}
.img-container img {
width: 100%;
height: 100%;
}
.text-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 2;
opacity: 0;
transition: opacity 0.5s ease;
background-color: rgba(0, 0, 0, 0.5);
color: #fff;
text-align: center;
padding-top: 50%;
pointer-events: none;
}
.img-container:hover .text-overlay {
opacity: 1;
}
```
上述CSS代码中,设置了容器的宽度和高度为200px,图片的宽度和高度为100%。设置文字的位置为绝对定位,覆盖在图片的上方,并且使用`opacity`属性将其隐藏。当鼠标悬停在容器上时,通过使用:hover伪类将文字的opacity属性设置为1,使其显示出来。
另外,为了避免鼠标事件被文字遮挡,需要使用`pointer-events: none;`属性来禁用文字上的鼠标事件。
最终的效果是当鼠标悬停在图片上时,会显示出图片下方的文字。
阅读全文
相关推荐


















