自阿里云官网UI升级后,对首页中的雪碧图动画很感兴趣。
d.png
于是和同事一起尝试自己写一下,用传统的雪碧图CSS3写法很生硬,而且死活无法实现动画中途回放的效果,于是同事小潘潘机智的通过js实现了,下面直接上代码。
后面抽时间给大家发vue版的,其实也是差不多的,改造一下就OK了。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>仿阿里云雪碧图动画</title>
<style type="text/css">
.xb {
/*background-color: antiquewhite;*/
background-image: url("./AI1.png");
width: 64px;
height: 64px;
background-repeat: no-repeat;
background-position: 0 0;
background-size: 100%;
background-position-y: 0;
cursor: pointer;
}
</style>
</head>
<body>
<div>
<div class="xb" id="xb" onmouseenter="mousemove()" onmouseleave="mouseleave()"></div>
<div id="text">雪碧图</div>
</div>
</body>
<script type="text/javascript">
var style='' // 样式
var bpy=0 // background-position-y
var mouseenters=null // 进入定时器
var mouseleave1=null // 离开定时器
var box = document.getElementById("xb"); // 获取节点对象
// 进入动画
function mousemove(e) {
clearInterval( mouseleave1)
console.log('鼠标移入', e)
mouseenters = setInterval(() => {
bpy += 64
console.log( bpy)
if ( bpy >= 1280) {
clearInterval( mouseenters)
}
box.style.backgroundPositionY = '-' + bpy + 'px'
}, 50)
}
// 离开
function mouseleave(e) {
clearInterval( mouseenters)
console.log('鼠标移出', e)
mouseleave1 = setInterval(() => {
bpy -= 64
console.log( bpy)
if ( bpy === 0) {
clearInterval( mouseleave1)
}
box.style.backgroundPositionY = '-' + bpy + 'px'
}, 50)
}
</script>
</html>