直接上代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
* {
padding: 0px;
margin: 0px;
}
body,
html {
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
}
body {
position: relative;
background-attachment: fixed;
}
#con{
width: 64px;
height: 64px;
background-position: 0 0;
background-size: 100%;
background-position-y: 0;
background-image: url("https://img.alicdn.com/tfs/TB1C7fPidTfau8jSZFwXXX1mVXa-128-2688.png");
background-repeat: no-repeat;
}
#con1{
width: 64px;
height: 64px;
background-position: 0 0;
background-size: 100%;
background-position-y: 0;
background-image: url("https://img.alicdn.com/imgextra/i4/19999999999999/O1CN019FqNuv2NjaswQicY2_!!19999999999999-2-tps.png");
background-repeat: no-repeat;
}
.out{
animation: playout 0.8s steps(20) forwards;
}
.out:hover {
animation: play 0.3s steps(20) forwards;
}
@keyframes play {
0% {
background-position: 0 0;
}
100% {
background-position: 0 -1280px;
}
}
@keyframes playout {
0% {
background-position: 0 -1280px;
}
100% {
background-position: 0 0;
}
}
#wrapper {
transform: translate(-50%, -50%);
position: absolute;
top: 50%;
left: 50%;
}
</style>
</head>
<body>
<div id="wrapper">
<div class="out" id="con"></div>
<div class="out" id="con1"></div>
</div>
</body>
</html>
注:以上是纯css实现。目前的问题是如果滑动太快,看起来会像是突变,感觉不太好。
搭配js实现以解决滑动太快造成的动画突变,代码如下:
<style>
* {
padding: 0px;
margin: 0px;
}
body,
html {
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
}
body {
position: relative;
background-attachment: fixed;
}
#con2 {
width: 64px;
height: 64px;
background-position-x: 0;
/*background-position-y: 0;*/
background-size: 100%;
background-image: url("https://img.alicdn.com/tfs/TB1C7fPidTfau8jSZFwXXX1mVXa-128-2688.png");
background-repeat: no-repeat;
}
</style>
<body>
<div id="con2" style="background-position-y:0" onmouseenter="mouseenter()" onmouseleave="mouseleave()"></div>
</body>
js:
<script type="text/javascript">
var timer;
var ele = document.getElementById('con2')
function mouseenter() {
var h = parseInt(ele.style.backgroundPositionY)
if (timer) {
clearInterval(timer)
}
timer = setInterval(() => {
h -= 64
if (h <= -1280) {
h = -1280
clearInterval(timer)
}
ele.style.backgroundPositionY = h + 'px'
}, 30)
}
function mouseleave() {
if (timer) {
clearInterval(timer)
}
var h = parseInt(ele.style.backgroundPositionY)
timer = setInterval(() => {
h += 64
if (h >= 0) {
h = 0
clearInterval(timer)
}
ele.style.backgroundPositionY = h + 'px'
}, 30)
}
</script>