Can you emulate the left-mouse button selection in JQuery?
I have a large number of DIVs aligned like this:
+---------------+
| DIV 1 |
+---------------+
| DIV 2 |
+---------------+
| DIV 3 |
+---------------+
| ... |
I want to change to toggle the class of each DIV when the user holds the left mouse button and hovers over them.
isMouseDown = false
$('body').mousedown(func开发者_如何学Gotion () {
isMouseDown = true;
})
.mouseup(function () {
isMouseDown = false;
});
$(".div").live("mouseenter", function () {
if (isMouseDown) {
$(this).toggleClass("selected");
}
});
I currently do it this way, but it only really works when the user is using the right mouse button, because the left button triggers the browser's default select behavior.
Is it possible to make this work with the left mouse as well?
EDIT: Working code:
isMouseDown = false
$('body').mousedown(function (e) {
e.preventDefault(); // Prevent default behavior
isMouseDown = true;
})
.mouseup(function (e) {
e.preventDefault(); // Prevent default behavior
isMouseDown = false;
});
$(".div").live("mouseenter", function (e) {
e.preventDefault(); // Prevent default behavior
if (isMouseDown) {
$(this).toggleClass("selected");
}
});
// Because IE8 won't get it without this...
$(".div").mousemove(function (e) {
if ($.browser.msie) {
e.preventDefault();
return false;
}
});
You basically want to prevent the browser events default behavior.
Then simply use jQuerypreventDefault
method.
isMouseDown = false
$('body').mousedown(function (e) {
e.preventDefault(); // Prevent default behavior
isMouseDown = true;
})
.mouseup(function (e) {
e.preventDefault(); // Prevent default behavior
isMouseDown = false;
});
$(".div").live("mouseenter", function (e) {
e.preventDefault(); // Prevent default behavior
if (isMouseDown) {
$(this).toggleClass("selected");
}
});
You could try preventing the default behavior of the browser click. jQuery disable a link
精彩评论