js实现元素抖动动画效果

js实现元素抖动动画效果

elShaking函数封装

给指定元素绑定mouseenter事件,当鼠标移入时,元素抖动

function elShaking(el) {
  const maxAngle = 7 // 震动偏移角度
  const interval = 12 // 震动快慢,数字越小越快,太小DOM反应不过来,看不出动画
  const quarterCycle = 6 // 一次完整来回震动的四分之一周期
  let curAngle = 0
  let direction = 1
  const timer = setInterval(function(){
    if (direction > 0) {
      curAngle++
      if (curAngle === maxAngle) {
        direction = -1
      }
    } else {
      curAngle--
      if (curAngle === -maxAngle) {
        direction = 1
      }
    }
    el.style.transform = 'rotate(' + curAngle + 'deg)';
  }, interval)
  setTimeout(function(){
    clearInterval(timer)
  }, maxAngle * interval * quarterCycle);
}

代码演示

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
	<style>
		.box{
			background-color: red;
			width: 100px;
			margin: 0 auto;
			margin-top: 200px;
			height: 100px;
		}
	</style>
</head>
<body>
	<div class="box" id="box"></div>
	<script>
		document.getElementById('box').addEventListener('mouseenter',function(e){
			elShaking(e.target)
		})
		function elShaking(el) {
			const maxAngle = 7 // 震动偏移角度
			const interval = 12 // 震动快慢,数字越小越快,太小DOM反应不过来,看不出动画
			const quarterCycle = 6 // 一次完整来回震动的四分之一周期
			let curAngle = 0
			let direction = 1
			const timer = setInterval(function(){
				if (direction > 0) {
				curAngle++
				if (curAngle === maxAngle) {
					direction = -1
				}
				} else {
				curAngle--
				if (curAngle === -maxAngle) {
					direction = 1
				}
				}
				el.style.transform = 'rotate(' + curAngle + 'deg)';
			}, interval)
			setTimeout(function(){
				clearInterval(timer)
			}, maxAngle * interval * quarterCycle);
		}
	</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值