JavaScript中的基础运动

l运动基础
•让Div运动起来
•速度——物体运动的快慢
l匀速运动
•速度不变
l运动框架
•在开始运动时,关闭已有定时器
•检测停止条件和执行运动对立(if/else)


/*
在js中,如果让一个页面元素动起来
*/
window.onload = function() {

var oBtn = document.getElementById('btn');
var oDiv = document.getElementById('div1');
var iTimer = null;

//点击按钮,让div1横向向右移动
//定时器

/*
1.清除定时器,保证运动过程中只有一个定时器在执行
2.开始定时器
3.开始运动(同时在运动加入判断,以便在需要的时候或者是满足某个要求停止运动)
*/
oBtn.onclick = function() {

clearInterval(iTimer);

iTimer = setInterval(function() {

//oDiv.style.left = oDiv.offsetLeft + 10 + 'px';
if (oDiv.offsetLeft == 500) {
clearInterval(iTimer);
} else {
oDiv.style.left = oDiv.offsetLeft + 10 + 'px';
}

}, 30);

}
}

posted @ 2015-09-24 19:39  小美_chen  阅读(84)  评论(0)    收藏  举报