定时器、函数封装

一、return返回值

1)函数+括号

2)所有函数默认返回值:未定义

3)return后任何代码都不执行

二、定时器

1.setInterval

1)是一个实现定时调用的函数

2)setInterval(函数,毫秒) 重复执行

3)clearInerval( )   清除

2.setTimeout

1)只执行一次

2)clearTimeout()清除

三、函数封装

 

oBtn1.onclick = function () {
	
	doMove ( oDiv, -12, 10 );

};
oBtn2.onclick = function () {
	
	doMove ( oDiv, 12, 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';
		
		if ( speed == target ) {
			clearInterval( obj.timer );
		}
		
	}, 30);
}

 

  

 

posted @ 2018-02-11 11:36  hey-李高冷  阅读(294)  评论(0编辑  收藏  举报