图片显示完毕后,img会成为“替换元素”,而替换元素是无法设置伪元素的,因为content内容被图片替换掉了;所以我们可以使用伪类,还需要注意attr里面的变量不能加双引号。
<div>
<img src="xxx.gif" alt="lululu">
</div>
<style>
div {
width: 100px;
height: 100px;
overflow: hidden;
}
img {
display: inline-block;
width: 100%;
height: 100%;
position: relative;
}
img::after {
content: attr(alt);/* 生成 alt 信息 */
position: absolute; left: 0;bottom: 0;right: 0;
background-color: rgba(0,0,0,.5);
transform: translateY(100%);/* alt 信息隐藏 */
transition: transform .2s;/* 过渡动画效果 */
}
img:hover::after {
transform: translateY(0);/* alt 信息显示 */
}
</style>
复制代码