在JavaScript或jQuery中检测鼠标的当前状态,即它的向下或向上

detecting the current state of a mouse in javascript or jquery i.e wheather its down or up

本文关键字:状态 jQuery JavaScript 检测 鼠标      更新时间:2023-09-26

我正在构建一个Web应用程序,该应用程序涉及从网页内和其他应用程序(例如word和pdf文档)中拖放大量文本。我需要获取鼠标的当前状态,如果它向下(单击)或向上(释放)。目前,如果我在网页内拖动文本,我能够获得鼠标的当前状态,但如果鼠标来自另一个应用程序,则无法获得鼠标状态,例如单词并拖动一些文本。任何获取鼠标向下或向上状态的指针都非常感谢。

据我了解,问题是,如果鼠标左键是在窗口外按下的(用于拖动操作),您需要确定是否按下鼠标左键。

存在许多问题:

  • 拖动操作期间不会触发鼠标移动事件
  • 浏览器之间当前按钮状态的数据不同

我想出了这个解决方案:

/**
 * keeps track of the current active mouse button.
 * @param notifier {Function} called when the active button is updated.
 * @param oneCallPerStateChange {Boolean} (defaults to false) if true the notifier will be called only when the active button changes.
 */
function initActiveButtonWatcher(notifier, oneCallPerStateChange) {
    // create variable to store button states.
    var _activeButton = -1, activeButton = 0
    // function to set the current active button.
    function updateMouseState(e) {
        // update active button.
        activeButton = typeof e.buttons === "number" ? e.buttons : e.which
        // notify if the active button is different.
        if ( oneCallPerStateChange? (_activeButton !== activeButton && typeof notifier === "function") : (typeof notifier === "function")) {
            notifier(activeButton)
        }
        // store the last state in order to be able to tell if the state has changed.
        _activeButton = activeButton
    }
    // function to get the current active button.
    function getButtonState() { return activeButton }
    // update the button state when the mouse is moved
    // or an item is dragged into the window.
    window.addEventListener("mousemove", updateMouseState, false)
    window.addEventListener("dragover", function() { updateMouseState({which: 1}) }, false)
    window.addEventListener("dragleave", function() { updateMouseState({which: 0}) }, false)
    // expose the getter on the global object.
    window.getButtonState = getButtonState
}

上述解决方案绑定到鼠标移动事件和拖拽事件。Chrome 在 dragover 事件中获取具有正确按钮值的有效事件对象,但我发现 FireFox 没有。我认为鼠标左键的状态在拖动操作期间非常明显,它会被按下,对吧?如果不单击和移动,则无法拖动。所以我只是在拖拽时将状态设置为 1(左下)。同样,在 dragleave 上,该值设置为零。

您将执行所有正常的拖动,拖动开始,结束,拖放等处理以防止默认浏览器操作,并且window.getButtonState()返回的值应始终是当前活动鼠标按钮的值。

下面是一些示例用法,它将页面中第一个 h1 标记的值设置为当前按下的按钮:

;(function() {
    var active = document.getElementsByTagName("h1")[0]
    function translate(n) {
        switch (n) {
            case 0:
                return "none"
                break;
            case 1:
                return "left"
                break;
            case 2: case 4: // Firefox calls it 4, the values differ between browsers I find.
                return "middle"
                break;
            case 3:
                return "right"
        }
    }
    initActiveButtonWatcher(
        function(currentActive) {
            active.innerHTML = "Active button: " + translate(currentActive)
        }
    )
})()

您必须对跨浏览器进行一些调整以处理不同的值(FF 报告中间按钮为 4 等),但您应该能够使用此方法合理地获得当前按钮。

试试看:http://jsfiddle.net/6BUA4/

当您在外部程序(如 Word)中选择文本并将其拖到网页上时,页面上的元素将生成dragenter Mouse 事件。我在Chrome中对此进行了测试,它对我有用。例如,我可以将dragenter侦听器绑定到 document.body 并接收事件,即使没有触发正常的鼠标事件:

function logEvent(e) {
    console.log(e);
}
document.body.addEventListener('dragenter', logEvent);
// MouseEvent {dataTransfer: Clipboard, toElement: body, ..., button: 0, ...}

也许您可以利用这一点来发挥自己的优势,因为dragenter事件意味着鼠标正在拖动并且必须按下按钮。此外,您可以通过从事件中获取数据来获取正在拖动的文本:

e.dataTransfer.getData('text/plain');

您需要在getData调用中使用正确的数据类型。我在Word中键入了一些文本,并能够使用text/plain获得拖动的文本。

有一个状态为: 演示 - 代码

var _isMouseDown = false;
$(document).on("mousedown", function(event) {
    _isMouseDown = true;
});
$(document).on("mouseup", function(event) {
    _isMouseDown = false;
});

然后,您可以检查_isMouseDown以查看鼠标是否关闭。

或更紧凑:演示 - 代码

$(document).on("mousedown mouseup", function(event) {
    _isMouseDown = event.type == "mousedown";
});

如果你不想要全局变量,你可以保存_isMouseDown抛出jQuery的data方法: 演示 - 代码

$(document).on("mousedown mouseup", function(event) {
    $(this).data( "_isMouseDown", (event.type == "mousedown") );
});

并检查投掷:$(document).data("_isMouseDown")


您正在寻找新的强大的HTML5拖放http://www.w3schools.com/html/html5_draganddrop.asp

您正在寻找的事件是"下降"

<div id="droppable" 
 ondragover="event.preventDefault()" 
 ondrop="event.preventDefault(); 
  console.log(event); 
  console.log(event.dataTransfer.getData('text/plain'))">

当然,您应该将此代码移动到js文件中,但这为您提供了已完成的示例。您可能想阅读外部下降的内容,甚至将其用于上传。

以下是有关事件.数据传输的详细信息http://www.tutorialspoint.com/html5/html5_drag_drop.htm