布朗运动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#box{width: 100px;height: 100px;border-radius: 50%;background: skyblue;position: absolute;left: 52px;top: 100px;}
.wall{width: 2px;height:500px;position: absolute;background: #000;}
.wr{left: 500px;}
.wl{left: 50px;}
</style>
</head>
<body>
<button id="btn">开始</button>
<p id="box"></p>
<p id="rwall" class="wall wr"></p>
<p id="lwall" class="wall wl"></p>
<script type="text/javascript">
var btn=document.getelementbyid("btn");
var o=document.getElementById("box");
var wl=document.getElementById("lwall");
var wr=document.getElementById("rwall");
var speed=5;
var t;
btn.onclick=function(){
t=setInterval(moveRight,20);
};
function moveRight(){
var wrl=parseInt(window.getComputedStyle(wr,null).left);
var ow=parseInt(window.getComputedStyle(o,null).width);
var l=parseInt(window.getComputedStyle(o,null).left);
if(ow+l>=wrl) {
clearinterval(t);
t=setInterval(moveLeft,20);
}else{
o.style.left=l+speed+'px';
}
}
function moveLeft(){
var wll=parseInt(window.getComputedStyle(wl,null).left);
var lw=parseInt(window.getComputedStyle(wl,null).width);
var l=parseInt(window.getComputedStyle(o,null).left);
if (l<=wll+lw) {
clearInterval(t);
t=setInterval(moveRight,20);
}else{
o.style.left=l-speed+"px";
}
}
</script>
</body>
</html>
相关阅读