2012-05-29 52 views
4

我想做一個非常簡單的應用程序,用戶可以在鼠標按鈕關閉時用選定的顏色繪製到表中,並且在鼠標啓動時事件停止。jQuery事件停止在mouseup上

繪圖效果很好,唯一的問題是當鼠標釋放時事件不會停止。 我嘗試過很多方式,但顯然我做錯了什麼。還嘗試綁定和解除綁定事件,但也沒有工作。

您可以在這裏看到的代碼的一個版本: http://jsfiddle.net/mFzkG/8/

任何幫助,非常感謝!

回答

4

您只需要從表格單元格綁定和取消綁定事件。

var currentColor; 
    $('.colors').click(function() { 
     $(this).fadeTo("fast", 0.40); 
     currentColor = $(this).css("background-color"); 
     $('.colors').not(this).fadeTo("fast", 1); 
    }); 


    $('table').mousedown(
    function() { 
     $('td').bind('hover', function(){ 
      $(this).css(
      "background-color", currentColor 
      );    
     }); 
     }).mouseup(function(){ 
      $('table td').unbind('hover'); 
      $('table').css(function(){ 
       return false; 
     }); 
     }); 


    $("#reset").click(function() { 
     $("td").css("background-color", "white") 
    } 
    ); 

,這裏是工作的jsfiddle http://jsfiddle.net/mFzkG/12/

+0

就像一個魅力!非常感謝Senad! – Zoltan

2

爲什麼不去做這樣的:

var currentColor; 
    var isMouseDown = false;  
    $('.colors').click(function() { 
     $(this).fadeTo("fast", 0.40); 
     currentColor = $(this).css("background-color"); 
     $('.colors').not(this).fadeTo("fast", 1); 
    }); 
    $('td').mousedown(function() {   
     isMouseDown = true; 
    }); 
    $('td').mouseup(function() { 
     isMouseDown = false; 
    }); 
    $('td').hover(function() { 
     if (isMouseDown) { 
      $(this).css("background-color", currentColor);  
     } 
    }); 
    $("#reset").click(function() { 
     $("td").css("background-color", "white") 
    }); 

所以,我認爲正確的實施方法是捕捉mouseup/mousedown事件,舉行狀態變量isMouseDown並在hover()函數中檢查此變量。

2

你也可以試試這個jQuery代碼:

$('table').mousedown(
function() { 
    $('td').bind('mousedown mousemove', function(){ 
     $(this).css(
     "background-color", currentColor 
     );    
    }); 
    }); 
$('table').mouseup(
    function() { 
     $('td').unbind('mousedown mousemove'); 
    });