js-定时器的应用,按键div控制向左移动

 封装一个左右移动的函数

	/*
				obj:要执行动画的对象
				target:执行的目标位置
				//左移动 目标最小 向右移动 目标最大 
				speed:移动的速度 传递的只有正值 这样可以使得原来的初始位置进行判断移到目标位置
				*/
				function move(obj, target, speed) {
					var dir = parseInt(getStyle(obj, "left")); //获取原来的样式值
					if(dir>target){
						speed=-speed;
					}
					clearInterval(timer);
					var timer = setInterval(function() {
						dir = dir + speed;
						//正数:右 负:左
						if (dir >= target && speed > 0 || dir <= target && speed < 0) {
							dir = target;
						}
						obj.style.left = dir + "px";
						if (dir == target) { //正好才会买组
							clearInterval(timer);
						}

					}, 30);
				};
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			* {
				margin: 0;
				padding: 0;
			}

			#box1 {
				height: 100px;
				width: 100px;
				background-color: red;
				margin-top: 20px;
				position: absolute;
				/* 	IE没有指定值的时候容易获取auto 所以我们最好指定 */
				left: 0px;
			}
		</style>
		<script>
			window.onload = function() {
				// setTimeout()	
				// clearTimeout()
				//
				var btn01 = document.getElementById("btn01");
				var btn02 = document.getElementById("btn02");
				var box1 = document.getElementById("box1");
				//保存定时器的标识
				var timer;
				btn01.onclick = function() {
			
					move(box1, 600, 10)
				}
				btn02.onclick = function() {
					move(box1, 0, 10)

				}
				/*
				obj:要执行动画的对象
				target:执行的目标位置
				//左移动 目标最小 向右移动 目标最大 
				speed:移动的速度 传递的只有正值 这样可以使得原来的初始位置进行判断移到目标位置
				*/
                var timer ;
				function move(obj, target, speed) {
					var dir = parseInt(getStyle(obj, "left")); //获取原来的样式值
					if(dir>target){
						speed=-speed;
					}
					clearInterval(timer);
					    timer = setInterval(function() {
						dir = dir + speed;
						//正数:右 负:左
						if (dir >= target && speed > 0 || dir <= target && speed < 0) {
							dir = target;
						}
						obj.style.left = dir + "px";
						if (dir == target) { //正好才会买组
							clearInterval(timer);
						}

					}, 30);
				};
				//obj获取的元素 name 样式名
				function getStyle(obj, name) {
					if (window.getComputedStyle) {
						return getComputedStyle(obj, null)[name]; //正常 
					}
					return obj.currentStyle[name]; //IE8--
				};


			};
		</script>
	</head>
	<body>
		<button id="btn01">点击按钮以后box1向右移动</button>
		<button id="btn02">点击按钮以后box1向左移动</button>

		<div id="box1"></div>
		<div
			style="width: 0; height: 1000px; border-left: 1px solid black;: 1px black solid; position: absolute; left: 600px;">
		</div>
		<div
			style="width: 0; height: 1000px; border-left: 1px solid black;: 1px black solid; position: absolute; left: 0px;">
		</div>
	</body>
</html>


版权声明:本文为weixin_47295886原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。