原生js setInterval函数使盒子左右移动动画及封装

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		body {
			margin: 0;
		}
		#box {
			width: 100px;
			height: 100px;
			background-color: pink;
			position: relative; /*右移位置改变脱离文档流*/
		}
		#box1 {
			width: 100px;
			height: 100px;
			margin-top: 10px;
			background-color: blue;
			position: relative; /*右移位置改变脱离文档流*/
		}
	</style>
</head>
<body>
	<input type="button" value="动画400" id="btn1">
	<input type="button" value="动画800" id="btn2">
	<div id="box"></div>
	<div id="box1"></div>
	<script>
		var btn1 = document.getElementById('btn1');
		var btn2 = document.getElementById('btn2');
		var box = document.getElementById('box');
		var box1 = document.getElementById('box1');
		
		// 1. 点击按钮让盒子向右移动  盒子从800 到400的速度很慢原因分析 解决:给body清空margin
		btn1.onclick = function () {
			animation(box, 400);
			animation(box1, 400);
			// console.log(box.style.left); // 第一次:空字符串  第二次:18px
			// console.log(box.offsetLeft); // 第一次:8 body自带的margin值  第二次:26=8+18
			// box.style.left = box.offsetLeft + 10 + 'px'; 
			// console.log(box.style.left); // 第一次:18 box设置的是相对定位,不包含body自带的margin值8px,而是相当于第一次的初始位置右移了8+10=8px 第二次:36px
			// console.log(box.offsetLeft); // 第一次:26  第二次:44=26+10+8 每次都加了一个body自带的margin值
		}

		btn2.onclick = function () {
			animation(box, 800);
			animation(box1, 800);
			// console.log(box.offsetLeft); // 第一次:44  第二次:42 每次只移动了很小的距离
			// console.log(box.style.left); // 第一次:36px  第二次:34px
			// box.style.left = box.offsetLeft - 10 + 'px';  
			// console.log(box.offsetLeft); // 第一次:42  第二次:40
			// console.log(box.style.left); // 第一次:34px  第二次:32px
		}

		// 动画封装
		// var timerId = null; // 需全局变量
		function animation(element, target) {
			// 给每个element增加一个属性timerId,保证定时器标志互不干扰
			if (element.timerId) {
				clearInterval(element.timerId);
				timerId = null;
			}
			element.timerId = setInterval(function () {
				// 步距
				var step = 6;
				var current = element.offsetLeft;
				// 盒子从400 到800 执行动画
				// 盒子从800 到400 不执行动画
				// 如果当前位置 > 目标位置 step < 0
				if (current > target) {
					step = -Math.abs(step);
				}

				// 当前位置和目标位置的差值小于step
				if (Math.abs(current - target) < Math.abs(step)) { 
					// 停止定时器
					clearInterval(element.timerId);
					element.style.left = target + 'px';  // 赋值为目标值
					// 退出函数
					return;
				};
				current += step;
				element.style.left = current + 'px';
			}, 30);
		}
		
	</script>
</body>
</html>

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值