回调函就是一个函数调用另一个函数的过程,在编码过程中我们经常会遇到在上一个函数执行完后,才开始执行下一个函数。
下面是代码生成一个div然后让他的左边距增加到100然后停止。
function fun1(){ var div =document.createElement(‘div‘); div.style.width = ‘100px‘; div.style.height = ‘100px‘; div.style.background =‘red‘; document.body.appendChild(div); var s = 0; var timer = null; timer = setInterval(function(){ s ++; if(s==1000){ clearInterval(timer); } div.style.marginLeft = s+‘px‘; },1); } fun1();
上面是我们经常会遇见的情况,当一个动态效果执行完后,我们会想接着再执行另一个事件,就需要把另一个函数当参数传递进去,当上一个函数执行完后,执行下一个函数。
代码如下。
fun1(fun2); function fun1(callback) { var div = document.createElement(‘div‘); div.style.width = ‘100px‘; div.style.height = ‘100px‘; div.style.background = ‘red‘; document.body.appendChild(div); var s = 0; var timer = null; timer = setInterval(function () { s++; if (s == 1000) { clearInterval(timer); callback(); } div.style.marginLeft = s + ‘px‘; }, 1); } function fun2() { var div1 = document.createElement(‘div‘); div1.style.width = ‘100px‘; div1.style.height = ‘100px‘; div1.style.background = ‘red‘; div1.style.marginTop = ‘100px‘; document.body.appendChild(div1); var s = 0; var timer = null; timer = setInterval(function () { s++; if (s == 1000) { clearInterval(timer); } div1.style.marginLeft = s + ‘px‘; }, 1); }
上面代码中fun2在fun1执行是被作为一个参数传进了,fun1里面。当fun1里s等于1000是,定时器停止然后开始执行fun2。
如果当fun2执行完后我们还需要回调,那么把另一个函数传入fun2就行了;
fun1(fun2); function fun1(callback) { var div = document.createElement(‘div‘); div.style.width = ‘100px‘; div.style.height = ‘100px‘; div.style.background = ‘red‘; document.body.appendChild(div); var s = 0; var timer = null; timer = setInterval(function () { s++; if (s == 1000) { clearInterval(timer); callback(fun3); //这里的callback()原型就是fun2,把fun3当做参数传进去,不要用fun3(),这样就是执行了; } div.style.marginLeft = s + ‘px‘; }, 1); } function fun2(callback) { var div1 = document.createElement(‘div‘); div1.style.width = ‘100px‘; div1.style.height = ‘100px‘; div1.style.background = ‘red‘; div1.style.marginTop = ‘100px‘; document.body.appendChild(div1); var s = 0; var timer = null; timer = setInterval(function () { s++; if (s == 1000) { clearInterval(timer); callback(); } div1.style.marginLeft = s + ‘px‘; }, 1); } function fun3() { var div1 = document.createElement(‘div‘); div1.style.width = ‘100px‘; div1.style.height = ‘100px‘; div1.style.background = ‘red‘; div1.style.marginTop = ‘100px‘; document.body.appendChild(div1); var s = 0; var timer = null; timer = setInterval(function () { s++; if (s == 1000) { clearInterval(timer); } div1.style.marginLeft = s + ‘px‘; }, 1) }
时间: 2024-10-12 04:33:04