JavaScript制作按钮控制圆移动效果

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
		*{padding: 0;margin: 0;}
		#box{width: 80px;height: 80px;background-color: red;border-radius: 50%;
			position: absolute;top: 100px;left: 50px;}
	</style>
</head>
<body>
	<button id="btn-left">向左</button>
	<button id="btn-right">向右</button>
	<button id="btn-top">向上</button>
	<button id="btn-bottom">向下</button>
	<div id="box"></div>
	<script type="text/javascript">
		var ball=document.querySelector('#box');
		var t;
		//向左移动
		document.querySelector('#btn-left').onclick=function(){
			clearInterval(t);//清除定时器
			//启动定时器
			t=setInterval(moveHor,10,-1);
		};

		//向右移动
		document.querySelector('#btn-right').onclick=function(){
			clearInterval(t);//清除定时器
			//启动定时器
			t=setInterval(moveHor,10,1);
		};

		//向上移动
		document.querySelector('#btn-top').onclick=function(){
			clearInterval(t);//清除定时器
			//启动定时器
			t=setInterval(moveVer,10,-1);
		};

		//向下移动
		document.querySelector('#btn-bottom').onclick=function(){
			clearInterval(t);//清除定时器
			//启动定时器
			t=setInterval(moveVer,10,1);
		};

		//水平移动
		function moveHor(speed){
			//获取当前左边距
			var preLeft=window.getComputedStyle(ball,null).left;
			preLeft=parseInt(preLeft);//去除单位
			ball.style.left=preLeft+speed+'px';
		}

		//垂直移动
		function moveVer(speed){
			//获取当前上边距
			var preTop=window.getComputedStyle(ball,null).top;
			preTop=parseInt(preTop);//去除单位
			//修改上边距
			ball.style.top=preTop+speed+'px';
		}
	</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_44830974/article/details/90017994