问题
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!
回答1:
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/
回答2:
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.
回答3:
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');
});
来源:https://stackoverflow.com/questions/10802184/jquery-event-to-stop-on-mouseup