创建时间:2022-05-06
效果图
<!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-image: url("https://img.alicdn.com/imgextra/i4/19999999999999/O1CN01S0iMLP2Njasz4Fk1Q_!!19999999999999-2-tps.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>
</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)
}
setInterval(_ => {
mousemove();
}, 3000)
setInterval(_ => {
mouseleave();
}, 4000)
</script>
</html>