2017-01-19 69 views

回答

0

https://jsfiddle.net/mzx79os2/13/

var $descriptionTextarea = $("textarea"); 
var $char_count = $(".char_count"); 
var textMax = 5; 
var animation, animationInProcess; 

$char_count.html(textMax + ' characters remaining'); 

function blinkStart(selfCharCounter) { 
    console.log('run blink'); 
    animationInProcess = true; 
    animation = setInterval(function(selfCharCounter){ 
     if(!animationInProcess){ 
     blinkStop(selfCharCounter) 
     return; 
     } 
     $(selfCharCounter).fadeOut(500).fadeIn(500); 
    }, 500, selfCharCounter); 
}; 

function blinkStop(selfCharCounter){ 
    console.log('stop blink'); 
    $(selfCharCounter).stop(true, true).show(); 
    clearInterval(animation); 
}; 

$descriptionTextarea.on("keyup",function(e){ 
    e.stopPropagation(); 
    var textLength = $(this).val().length; 
    var textRemaining = textMax - textLength; 
    var selfCharCounter = $(this).next(); 

    if(textRemaining <= 0){ 
     (!animationInProcess) && blinkStart(selfCharCounter); 
     selfCharCounter.css("color","red"); 
    }else{ 
     animationInProcess = false; 
     selfCharCounter.css("color",""); 
    } 

    selfCharCounter.html(textRemaining + ' characters remaining'); 
}); 
+0

請您編輯我的小提琴鏈接和更新there..and解釋我在短暫的 – Chandrakant

+0

請加解釋。 – Rajesh

+0

有一刻,我改寫了代碼 –

1
var descriptionTextarea = $("textarea"); 
var char_count = ".char_count"; 
var textMax = 5; 
var isRunning = false; 
var clearInt = 0; 
$(char_count).html(textMax + ' characters remaining'); 
descriptionTextarea.on("keyup", function(e) { 
    e.stopPropagation(); 

    var textLength = $(this).val().length; 
    var textRemaining = textMax - textLength; 
    var selfCharCounter = $(this).parent().find(char_count); 

    function blink() { 
    $(selfCharCounter).fadeOut(500).fadeIn(500); 
    }; 

    if (textRemaining <= 0 && !isRunning) { 
    selfCharCounter.css("color", "red"); 
    clearInt = setInterval(blink, 500); 
    isRunning = true; 
    } else if (textRemaining > 0 && isRunning) { 
    isRunning = false; 
    selfCharCounter.css("color", ""); 
    $(selfCharCounter).stop(true, true).fadeOut(); 
    $(selfCharCounter).stop(true, true).fadeIn() 
    clearInterval(clearInt); 
    clearInt = 0; 
    } 
    selfCharCounter.html(textRemaining + ' characters remaining'); 
}); 

有你的代碼中的多個問題:

  1. 在你的情況clearInt設置的KEYUP處理器中(所以以後每按鍵重置clearint爲0,所以你不清除正確的)
  2. 你在每一個按鍵設置多個間隔,你只是刪除最後一個,如果不是一個已經運行
  3. 停止動畫,你應該使用jQuery
  4. stop方法,你應該只添加一個區間
  5. 你也應該貼上問題的代碼SO
+0

請你解釋一下! – Chandrakant

+0

@Chandrakant看到我的編輯 – trebor

+0

你的代碼中的另一個問題是 - 它刪除/切換每個keyup上的CSS – Chandrakant

2

我已經看着你附加的小提琴。這裏有兩個問題,

  1. keyup你在KEYUP每次連接jQuery animations。所以clearing的間隔不會幫助你。
  2. jQuery的動畫必須停止使用$(element).stop(true, true)

我已經更新了的jsfiddle並還增加了檢查isBlinking附加動畫只有一次。

檢查此鏈接

https://jsfiddle.net/mzx79os2/8/