布朗运动
<!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="wall-right" class="wall wr"></p>
<p id="wall-left" class="wall wl"></p>
<script type="text/javascript">
//offsetleft/Right/Top/Bottom 只读属性
//offsetwidth offsetheight
//查找元素
var box=document.getelementbyid('box');
var wallRight=document.getElementById('wall-right');
var wallLeft=document.getElementById('wall-left');
var speed=2;//速度
var timer;
//获取右墙的左边距
var wR=wallRight.offsetLeft;
//获取左墙的左边距
var wL=wallLeft.offsetLeft;
//获取小球宽度
var width=box.offsetWidth;
//小球位移最大左边距
var maxLeft=wR-width;
//开始 点击事件
document.getElementById('btn').οnclick=function () {
moveRigth();
};
//向右移动
function moveRigth(){
//启动定时器
timer=setInterval(function(){
var l=box.offsetLeft;//取出当前left值
//到达边界,停止定时器
if(l>=maxLeft){
clearinterval(timer);
moveLeft();//向左移动
}else{
box.style.left=l+speed+'px';
}
},10);
}
//向左移动
function moveLeft(){
timer=setInterval(function(){
var l=box.offsetLeft;//取出当前left值
if(l<=wL){
clearInterval(timer);//停止向左移动
//向右
moveRigth();
}else{
box.style.left=l-speed+'px';
}
},10);
}
</script>
</body>
</html>
相关阅读
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> #box