1. 效果图
2. 代码
图片及源码的github链接
012.定时器动画
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>012.定时器动画</title>
<script type="text/javascript">
window.onload = function () {
var oDiv = document.getElementById('div1');
var iLeft = 0; // 左边距离
var iMove = 20; // 移动中间量
var iSpped = 2; // 移动速度
var timer = setInterval(moving, 30); // 每30毫秒运行moving
function moving(){
// 移动到位置1000
if(iLeft >= 1000){
// clearInterval(timer); // 停止定时器
iMove = -iSpped;
}
else if(iLeft < 0){
// clearInterval(timer); // 停止定时器
iMove = iSpped;
}
iLeft += iMove; // 每次运行距离加3px
oDiv.style.left = iLeft + 'px';
}
}
</script>
<style type="text/css">
.box{
width: 200px;
height: 200px;
background-color: gold;
position: absolute;
left: 0;
top: 100px;
}
</style>
</head>
<body>
<div id="div1" class="box"></div>
</body>
</html>