在黑马前端课程中学到了这一部分的内容,也查看了很多前辈的实现方法。比较常见的是使用伪元素来进行背景图片的切换。
我在实现的过程中受精灵图的启发,想到可以调整background-position来完成切换,代码少了不少,而且只需要使用一张背景图片。
效果图:
因为小米官网换了新图标没有使用这个效果了,所以随便找了个素材进行功能演示,原理是相同的。
代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
<style>
.box {
position: relative;
top: 100px;
left: 100px;
width: 134px;
height: 127px;
border: 1px solid slateblue;
}
.box .logo {
position: absolute;
width: 100%;
height: 100%;
background: url(images/game-icon-switch.png) no-repeat -10px -21px;
transition: all .4s;
background-position: 0 0;
}
.box .logo:hover {
/*通过改变position来切换位置*/
background: url(images/game-icon-switch.png) no-repeat -140px -21px;
}
</style>
</head>
<body>
<div class="box">
<a href="#" class="logo"></a>
</div>
</body>
</html>