可以't调用函数

Can't Call a Function

本文关键字:调用 函数 可以      更新时间:2024-04-08

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

所以我有一个淡入淡出功能,先淡入图像,然后淡出。我希望图像先淡入、更改,然后淡出。问题是,我能让img淡出的唯一方法是,如果我把它放在这样的按钮里。

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

我希望它像这个

Img显示

用户点击一个按钮

图像淡入,然后更改。

图像逐渐消失。

现在是这样的。

Img显示

用户点击一个按钮

图像淡入,然后更改。

用户点击另一个按钮

图像逐渐消失。

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

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);

但如果我把它们放在同一个函数中,它将不起作用。有什么帮助吗?

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

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

我认为您的问题在于绑定this。当从按钮的点击处理程序中调用函数时,this被设置为该按钮节点。您可以使用call功能手动设置this对象

var button = document.getElementById('hide-id');
fadeEffect.init.call(button,'chestImg', 0);

为什么要写";。调用(这个)";在javascript匿名函数的末尾?