문제

I am trying to make a very simple application where the user can draw into a table with a selected color when the mouse button is down, and the event stops when the mouse is up.

The drawing works well, the only problem is that the event doesn't stop when the mouse is released. I've tried it in many ways, but obviously I am doing something wrong. Also tried to bind and unbind the event, but didn't work either.

You can see one version of the code here: http://jsfiddle.net/mFzkG/8/

Any help much appreciated!

도움이 되었습니까?

해결책

All you have to do is bind and unbind event from table cell.

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

And here is working jsFiddle http://jsfiddle.net/mFzkG/12/

다른 팁

Why not do it like this:

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

So, I think the correct implementation would be to capture the mouseup/mousedown events, hold the state in a variable isMouseDown and check this variable in the hover() function.

You might also try this jquery code :

$('table').mousedown(
function() {
    $('td').bind('mousedown mousemove', function(){
        $(this).css(
        "background-color", currentColor
        );            
    });
    });
$('table').mouseup(
    function() {
        $('td').unbind('mousedown mousemove');
    });
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top