<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.room{
width: 500px;
height: 500px;
border: 1px solid black;
}
.ball{
width: 100px;
height: 100px;
background-color: red;
border-radius: 50%;
margin-top: 200px;
text-align: center;
}
</style>
</head>
<body>
<div class="room">
<div class="ball"></div>
</div>
</body>
<script type="text/javascript">
//获取元素
var ball=document.getElementsByClassName('ball')[0];
//定义一个初始值
var left=0;
//定义一个速度
var speed=2;
//定义一个定时器 动态改变属性
var timer=setInterval(function(){
left+=speed;
if(left==400||left==0){
speed=speed*-1;
}
ball.style.marginLeft=left+"px";
},30);
</script>
</html>