jQuery中的控件对象闪烁

Blinking control object in jQuery

本文关键字:对象 闪烁 控件 jQuery      更新时间:2023-09-26

我正在尝试使一个对象开始/停止闪烁(对于jquery中的对象,使用fadeIn((和fadeOut((。我已经有了一个方法blink((,它可以让元素闪烁一次,而且它很有效,但我正试图让它再次闪烁,作为对fadeOut((的回调,似乎无法在不出现堆栈溢出的情况下实现它。这就是我目前所掌握的:

     Indicator = function(str) {
        this.el= $(str);    
        this.blink = function(){ 
            var callback = function() { 
                                return function(){
                                    console.log(this.el)
                                    this.blink();
                                }.apply(this);
                                //if (!this.stopped)
                                    //this.blink();
                            }.apply(this);

            this.el.fadeIn(200).delay(200).fadeOut(200,callback);
            }
            this.stopped = false;
            this.stop = function() { this.stopped = true; }
    }
    function start(){
       indicator =new Indicator('#indicator p');
       indicator.blink();
    }

(我知道我的苹果((一团糟,对不起(

您已经创建了显式的无休止递归。您调用的是调用blinkfadeOut,调用callbackblink。我建议你用setInterval重写这个函数,比如:

this.fadeDuration = 200;
this.blinkIntervalRef = null;
this.blink = function(){
    this.blinkIntervalRef = setInterval(
         function(){this.doBlink();},
         this.fadeDuration*3
    );
}
this.stop = function() {clearInterval(this.blinkIntervalRef );}
this.doBlink = function(){
    //this is just shortcut, not to make horizontal scroll
    var interval = this.blinkIntervalRef; 
    this.el.fadeIn(interval).delay(interval).fadeOut(interval);
}

请注意,它没有经过测试,但至少它会给你一个方向。

更新:这是一个工作示例,但需要一些调试和时间跨度调整:

Indicator = function(str) {
    this.el= $(str);    
    this.fadeDuration = 100;
    this.blinkIntervalRef = null;
    this.doBlink = function(){
        //this is just shortcut, not to make horizontal scroll
        var interval = this.blinkIntervalRef; 
        this.el.fadeIn(interval).delay(interval).fadeOut(interval);
    }
    this.blink = function(){
        var ctx = this;
        this.blinkIntervalRef = setInterval(function(){ctx.doBlink();},this.fadeDuration*4);
    }
    this.stop = function() {clearInterval(this.blinkIntervalRef);}
}
function start(){
   indicator = new Indicator('#indicator p');
   indicator.blink();
}
$(document).ready(function(){start();});

这就是我曾经做过的类似事情:

function initializeBlink()
{      
        $('#indicator p').fadeToggle('slow', fadeToggleBlinker);
}
function fadeToggleBlinker()
{      
        var timeout = 2000;
        if(this.style.display == 'none')
                timeout = 1000;
        var tmp = $(this);
        window.setTimeout(function(){tmp.fadeToggle('slow', fadeToggleBlinker)}, timeout);
}