开发者

Dynamically set events and closure

This is a follow up question to my previous one: I have this object:

var myObject {
 init: function(){

        for (var i = 0; i <3; i++) {
            image = new Image();
.
.
.
            image.onmouseover = this.Fade(this, 70, 100,1);
            image.onmouseout = this.Fade(this, 100, 70,0);
         }
    },

SetOpacity: function (eID, opacity){                   
       eID.style.opacity = opacity / 100; 
       eID.style.filter = 'alpha(opacity=' + opacity + ')'; 
    } ,
    fade: function (eID, startOpacity, endOpacity){            
        var timer = 0; 
        if (startOpacity < endOpacity) {  
          for (var i = startOpacity; i <= endOpacity; i++) { 
 开发者_StackOverflow            (function(opacity) { 
                setTimeout(function() {SetOpacity(eID, opacity);}, timer * 30); 
             })(i); 
             timer++; 
           }     
        }            
    } 
}

Do I need to define closures on the events?


Yes.

Otherwise, the image variable will be shared by all three sets mouse handlers, and all of the animations will happen to the last image (even if you mouseover a different image).

Also, in your setTimeout callback, you should be writing MySlideshow.setOpacity.

EDIT: Your code (image.onmouseover = this.Fade(this, 70, 100,1)) is calling the Fade method and assigning the function that it returns to the onmouseover property. Since the Fade method doesn't return a function, it doesn't work.

You need to change it to image.onmouseover = function() { MySlideShow.Fade(this, 70, 100, 1); };.
That won't work as expected either unless you put it in a separate function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜