JS-定时器管理实例函数封装

时间:2022-02-07 22:49:50
/**
* Created by 12461 on 2016/11/6.
*/
window.onload = function () {
var oBtn1 = document.getElementById('btn1');
var oBtn2 = document.getElementById('btn2');
var oDiv = document.getElementById('div1');
//外面尽量不要放变量
// var timer = null;
oDiv.timer = null;
oBtn1.onclick = function () {
doMove(oDiv,-10,10);
};
oBtn2.onclick = function () {
doMove(oDiv,10,800);
};
//运动的函数
function doMove(obj,dir,target) {
//先清除定时器
clearInterval(obj.timer);
//设置定时器
obj.timer = setInterval(function () {
var speed = parseInt(getStyle(obj,'left')) + dir ;
//往前跑
if (speed > target && dir>0){
speed = target;
}
//往后跑
if (speed < target && dir < 0){
speed = target;
}
obj.style.left = speed + 'px';
},30);
}
//拿到样式的函数
function getStyle(obj,attr) {
return obj.currentStyle?obj.currentStyle[attr]:getComputedStyle(obj)[attr];
}
};