写了一个移动小球碰撞边框的练习题,本来以为很简单,结果在细节上卡了几个小时,目前问题是想让小球在途中随机变向,不知道怎么实现。
<html>
<head>
<style type="text/css">
#box{
width:500px;
height:500px;
border: 1px solid red;
position: relative;
}
#q{
position:absolute;
width: 50px;
height: 50px;
background: red;
border-radius:50%;
box-shadow: 1px 1px 1px gray;
}
</style>
</head>
<body>
<div id="box">
<div id="q"></div>
</div>
<script language="javascript">
var k1=Math.random()*5, k2=Math.random()*5, a=0, b=0;
function move () {
a=a+k1;
b=b+k2;
if (a<=0||a>500-50) {k1=-k1};
if (b<=0||b>500-50) {k2=-k2};
q.style.left = a + "px";
q.style.top = b + "px";
setTimeout('move()',10);
}
move()
</script>
</body>
</html>