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>