您可以模拟JQuery中的鼠标左键选择吗? [英] Can you emulate the left-mouse button selection in JQuery?

查看:139
本文介绍了您可以模拟JQuery中的鼠标左键选择吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多这样排列的DIV:

I have a large number of DIVs aligned like this:

+---------------+
| DIV 1         |
+---------------+
| DIV 2         |
+---------------+
| DIV 3         |
+---------------+
| ...           |

当用户按住鼠标左键并悬停在它们上时,我想更改每个DIV的类.

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?

工作代码:

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.

然后只需使用jQuery preventDefault 方法.

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

这篇关于您可以模拟JQuery中的鼠标左键选择吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆