效果演示
这个效果的制作是借助setTimeout的第三个参数。setTimeout/setInterval,这两个函数相信前端开发同学都很熟悉。它们在非IE(6-9)浏览器中还可以如下使用:
view sourceprint?1 | setTimeout( function (obj){ |
即传了第三个参数,第三个参数将作为回调函数的参数obj传入。在非IE浏览器中都弹出了1。这样有个好处,即解决了回调函数的执行上下文,比如要调用某个对象的某个方法,即可以通过参数把该对象传进去。
view sourceprint?1 | setTimeout( function (obj){ |
上次看到一个setTimeout的一个用法:
view sourceprint?1 | var arr = [1,9,2,8,3,7,4,6,4,5]; |
2 | for ( var i = 0, len = arr.length; i < len; i++){ |
虽然这个并不是什么好的用法,这里setTimeout的第三个参数主要得到了除IE外的系列浏览器的支持。
要让IE支持的话,可以按下面方法进行扩展:
view sourceprint?03 | if (!+[1,]){ //除IE外,!+[1,]都是返回false |
05 | w.setTimeout = overrideFn(w.setTimeout); |
06 | w.setInterval = overrideFn(w.setInterval); |
07 | })( function (originalFn){ |
08 | return function (code,delay){ |
09 | var args = Array.prototype.slice.call(arguments,2); |
10 | return originalFn( function (){ |
11 | if ( typeof code == 'string' ){ |
如果有第三个参数,某些情况下的调用就可以方便的处理回调函数中当前对象的问题,写起来好看点。扩展一下Function,增加一个延时调用(参考而已):
view sourceprint?01 | function .prototype.delay = function (){ |
02 | var args = Array.prototype.slice.call(arguments,0); |
03 | setTimeout( function (fn){ |
04 | fn.apply( '' ,args.slice(1)); |
10 | fn.delay(1000, 'xesam' ); |
下面是模拟进度条的代码:
view sourceprint?01 | <script type= "text/javascript" > |
02 | function Load(id,width){ |
03 | this .ele = document.getElementById(id); |
04 | this .indicator = document.createElement( 'div' ); |
05 | this .width = (width > 0 && width) || 300; |
11 | this .ele.style.width = this .width + 'px' ; |
12 | this .ele.appendChild( this .indicator); |
13 | var iStyle = this .indicator.style; |
16 | iStyle.background = '#ff5500' ; |
23 | this .timer = setTimeout( function (obj){ |
24 | var t = obj.indicator.data || 0; |
26 | obj.indicator.style.width = t + 1 + 'px' ; |
27 | obj.indicator.data = t + 1; |
30 | clearInterval(obj.timer); |
35 | clearTimeout( this .timer); |
38 | var load_1 = new Load( 'loading' ,300); |