2013-11-21 51 views
0

因爲我不是在CSS好,我想模擬按下的按鈕行爲(:活躍我覺得..)通過添加CSS 「光暈」類與jQuery addClass再DIV有點延遲Jquery的removeClass不起作用

後刪除這是我寫的代碼:

$(".cpUpbtnsclass").on('click', function() { 

     console.log($(this).attr('id')+" is clicked and a class will be added ! "); 

      $(this).addClass("glow"); 

     setTimeout(function(){ 
      $(this).removeClass("glow"); 
     },300); 
    }); 

,這是我想補充類:

.glow { 
box-shadow: 0px 0px 15px 5px rgba(255, 255, 190, .75); 
} 

我看到GL流影響加入addClass但我沒有看到它後300毫秒消失。

回答

2

超時創建一個新的範圍,其中this不再元素:

$(".cpUpbtnsclass").on('click', function() { 
    var self = this; 

    $(this).addClass("glow"); 

    setTimeout(function(){ 
     $(self).removeClass("glow"); 
    },300); 
}); 
2

嘗試

$(".cpUpbtnsclass").on('click', function() { 
    var this1 = $(this); //cache your selector 
    this1.addClass("glow"); 
    setTimeout(function() { 
     this1.removeClass("glow"); //use cached selector 
    }, 300); 
}); 


超時創建一個新的範圍,使您的 $(this)是不是你認爲裏面元素 setTimeout

1
$(function(){ 
    $(document).on('click', '.cpUpbtnsclass', function(){ 
     console.log($(this).attr('id')+" is clicked and a class will be added ! "); 
      $('.cpUpbtnsclass').addClass("glow"); 
     setTimeout(function(){ 
      $('.cpUpbtnsclass').removeClass("glow"); 
     },300); 
    }) 
}) 

演示這裏http://jsfiddle.net/N5Kk6/