无法调用函数

时间:2013-12-07 03:43:09

标签: javascript html image

JFiddler - http://jsfiddle.net/x2Uwg/

所以我有一个淡入淡出功能,它首先淡化图像,然后逐渐消失。我希望图像淡入,改变然后淡出。问题是我可以让img淡出的唯一方法是,如果我在这样的按钮中有它。

<button class="hide2" onclick="fadeEffect.init('chestImg', 0)">Fade Out</div>

我希望它是这样的

  

Img是show

     

用户点击一个按钮

     

图像淡入,然后发生变化。

     

图片淡出。

现在就是这样。

  

Img是show

     

用户点击一个按钮

     

图像淡入,然后发生变化。

     

用户点击另一个按钮

     

图片淡出。

我的淡入淡出功能看起来像这样。

var fadeEffect=function(){
return{
    init:function(id, flag, target){
        this.elem = document.getElementById(id);
        clearInterval(this.elem.si);
        this.target = target ? target : flag ? 100 : 0;
        this.flag = flag || -1;
        this.alpha = this.elem.style.opacity ? parseFloat(this.elem.style.opacity) * 100 : 0;
        this.elem.si = setInterval(function(){fadeEffect.tween()}, 20);
    },
    tween:function(){
        if(this.alpha == this.target){
            clearInterval(this.elem.si);
        }else{
            var value = Math.round(this.alpha + ((this.target - this.alpha) * .05)) + (1 * this.flag);
            this.elem.style.opacity = value / 100;
            this.elem.style.filter = 'alpha(opacity=' + value + ')';
            this.alpha = value
        }
    }
}
}();

我称之为淡入淡出

fadeEffect.init('chestImg', 1);

就像这样淡出

fadeEffect.init('chestImg', 0);

但如果我将它们放在同一个功能中,它将无法工作。有什么帮助吗?

2 个答案:

答案 0 :(得分:3)

当你在同一个函数中同时调用fadeEffect.init('chestImg', 1);fadeEffect.init('chestImg', 0);时,两个效果同时运行,我认为这会导致你的问题。我认为你需要做的是:

fadeEffect.init('chestImg', 1);
setTimeout(function(){fadeEffect.init('chestImg', 0);},20);

答案 1 :(得分:0)

我相信你的问题在于绑定this。从按钮的clickhandler中调用函数时,this将设置为该按钮节点。您可以使用this函数

手动设置call对象
var button = document.getElementById('hide-id');

fadeEffect.init.call(button,'chestImg', 0);

Why write ".call(this)" at the end of an javascript anonymous function?

相关问题