JS 向不同方向的动画效果 碰到墙停止

编程过程
1.设置一个圆的样式的div,让圆进行以后的移动主体;
2.添加控制上下左右四个按钮并添加鼠标点击事件;
3.找他们各自的id;
4.移动的原理是X轴 Y轴发生偏移,也就是移动时的left right top bottom值的变化;
5.定时器,每次移动的距离。

#box{//css样式
width: 100px;
height: 100px;
border-radius: 50%;
background: #f60;
margin-top: 20px;left:0;
position: absolute;}
    <button id="bleft">左</button>
	<button id="bright">右</button>
	<button id="btop">上</button>
	<button id="bbottom">下</button> 
	<div id="box"></div> //移动的div
	
<script>
		var oBox=document.getElementById('box');
		var speed=5;//每次移动距离
		var timer;//储存上个时间段
		document.getElementById('bleft').onclick=function(){//点击向左移动
           clearInterval(timer);//停止移动
           timer=setInterval(move,20,-speed,'left');//定时器调用函数每隔20毫秒left值为负数向左移动
		}
		document.getElementById('bright').onclick=function(){
			clearInterval(timer);
			timer=setInterval(move,20,speed,'left')
		}
		document.getElementById('btop').onclick=function(){
			clearInterval(timer);
			timer=setInterval(move,20,-speed,'top')
		}
		document.getElementById('bbottom').onclick=function(){
			clearInterval(timer);
			timer=setInterval(move,20,speed,'top')
		}
		function move(speed,pre){//函数的两个参数,一个为移动的速度(距离)一个为属性(left top bottom right...)
           var o=window.getComputedStyle(oBox,null)[pre];获取oBox的属性
           o=parseInt(o);数值类型
           oBox.style[pre]=o+speed+'px';字符串拼接,oBox的sytle的属性  
		}

2.碰到墙壁停止运动
也就是说移动方向的值等于墙壁距离的值

<button id="move">运动</button>//按钮用来添加点击事件
	<div id="box"></div>//移动的div
	<div id=box2></div>//墙壁
<script>
		var oBox=document.getElementById('box');
		var oBox2=document.getElementById('box2');
		var oB2=parseInt(window.getComputedStyle(oBox2,null).left);找到墙壁的左距离的值转化为数值类型;
		var speed=10;//每次移动的距离
		var timer;  储存上个时间段
		document.getElementById('move').onclick=function(){
           timer=setInterval(demo,20)//定时器调用函数每隔20毫秒变化一次
		}
		function demo(){
			var c=parseInt(window.getComputedStyle(oBox,null).left);//获取oBox的left值储存在变量c中并转为数值类型
			if (c>=(oB2-100)) {//判断oBox的left值是否等于墙壁距离的值(100为oBox的直径 若不减去则会停在墙壁后面)
				clearsetInterval(timer)条件成立停止移动
			}else{不成立则继续移动
				oBox.style.left=c+speed+'px';left的值
			}
		}
	</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值