作业笔记

188 阅读2分钟

来自妙味课堂study.miaov.com/v_show/1024的小练习

对于这个+1挨个上飘的实现我写了一个函数

这是js

function doMove( obj,attr,step,edStep,delay,frame ){		
    //delay是延迟多少毫秒
    //frame是每个几ms执行一次,相当于帧数

	obj.timer = setTimeout(function timer(Xframe){

		//找出对于属性值提取整数部分
		var speed = parseInt(getStyle(obj,attr));


		//判断,如果终点小于当前位置,则说明要向左或向上移动,step为负
		(edStep < speed) && (step = -step);
		
		speed += step;


		if( step > 0 ){
			//step大于0说明终点大于起点,如果当前位置大于终点,则止步与终点处
			(speed >= edStep) && ((speed = edStep));
		}else{
			(speed <= edStep) && (speed = edStep);

			
		}

		obj.style[attr] = speed + "px";

		if( speed != edStep ){
			setTimeout( function(Xframe){
				timer(Xframe);
			},Xframe,Xframe );
			console.log(Xframe);
		}else{
			clearTimeout(obj.timer);
			obj.timer = null;
		}
		
	},delay,frame);


}

这是.html

<script src="doMove.js"></script>
<script>
var oDiv = document.getElementsByTagName('div');
    
    for(var i=0; i<oDiv.length; i++){
    	doMove( oDiv[i],'left',15,600,250*i,30 )
    }
</script>

<div id="div" style=" width: 100px; height: 100px; position: absolute; left: 100px; top: 100px; background: red;"></div>
<div id="div" style=" width: 100px; height: 100px; position: absolute; left: 100px; top: 200px; background: red;"></div>
<div id="div" style=" width: 100px; height: 100px; position: absolute; left: 100px; top: 300px; background: red;"></div>
<div id="div" style=" width: 100px; height: 100px; position: absolute; left: 100px; top: 400px; background: red;"></div>
<div id="div" style=" width: 100px; height: 100px; position: absolute; left: 100px; top: 500px; background: red;"></div>
<div id="div" style=" width: 100px; height: 100px; position: absolute; left: 100px; top: 600px; background: red;"></div>
<div id="div" style=" width: 100px; height: 100px; position: absolute; left: 100px; top: 700px; background: red;"></div>


涉及到的知识点

为什么不用setInterval而用setTimeout

juejin.cn/post/684490…**

因为setTimeout可以保证当前的函数执行完后再执行下一次

怎样给定时器传值

30是多久执行一次 5是传给function的函数

setTimeout(function(x){
    console.log(x);
},30,5);

另外setTimeout里面的函数还可以是要有名字的函数

setTimeout(function timer(x){
    console.log(x);
    setTimeout(timer,30);
},30,5);

不过这里的timer不能加()不然函数会立即执行,不等你

over