Can you emulate the left-mouse button selection in JQuery?

非 Y 不嫁゛ 提交于 2019-12-12 00:47:11

问题


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(function () {
    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;
    }
});

回答1:


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



回答2:


You could try preventing the default behavior of the browser click. jQuery disable a link



来源:https://stackoverflow.com/questions/7254890/can-you-emulate-the-left-mouse-button-selection-in-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!