码迷,mamicode.com
首页 > 其他好文 > 详细

一个简单的触壁反弹

时间:2016-11-14 12:13:32      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:pad   document   doc   int   eth   back   math   poi   offset   

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title></title>

<style type="text/css">

*{

padding: 0;

margin: 0;

}

#box{

width: 500px;

height: 350px;

border:1px solid #ccc;

margin: 20px auto 0;

position: relative;

}

#ball{

width: 50px;

height: 50px;

background: red;

position: absolute;

top:0;

left: 0;

}

#btn{

width: 50px;

height: 50px;

/*光标出现小手*/

cursor: pointer;

background: green;

}

</style>

 

</head>

<body>

<div id="box">

<div id="ball">

 

</div>

</div>

<div id="btn">

 

</div>

</body>

</html>

<script type="text/javascript">

var box=document.getElementById("box");

var ball=document.getElementById("ball");

var btn=document.getElementById("btn");

var speedX=10;//横向的移动速度

var speedY=10;//横向的移动速度

//点击更改ball的速度

btn.onclick=function(){

speedX=parseInt(Math.random()*4+1)+2;

speedY=parseInt(Math.random()*4+1)+2;

}

setInterval(function(){

ball.style.left=ball.offsetLeft+speedX+"px";

ball.style.top=ball.offsetTop+speedY+"px";

//判断ball的位置 触壁speed取反

if(ball.offsetLeft>=box.clientWidth-ball.offsetWidth||ball.offsetLeft<=0){

speedX*=-1;

}

if(ball.offsetTop>=box.clientHeight-ball.offsetHeight||ball.offsetTop<=0){

speedY*=-1;

}

},30)

</script>

一个简单的触壁反弹

标签:pad   document   doc   int   eth   back   math   poi   offset   

原文地址:http://www.cnblogs.com/jwhgz/p/6061035.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!