通过background-position位移效果实现类似阿里云tab切换动画

直接上代码:

<!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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值