最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

I am building a web application that involves alot of dragging and dropping of text from within the web page and from other applications eg word and pdf documents. I need to get the current state of the mouse if its down(clicked) or up(release). Currently I am able to get the current state of the mouse if I am dragging text within the web page but am not able to get the mouse state if the mouse is ing from another application say word and its dragging some text. Any pointers to get the down or up state of the mouse are really appreciated.

I am building a web application that involves alot of dragging and dropping of text from within the web page and from other applications eg word and pdf documents. I need to get the current state of the mouse if its down(clicked) or up(release). Currently I am able to get the current state of the mouse if I am dragging text within the web page but am not able to get the mouse state if the mouse is ing from another application say word and its dragging some text. Any pointers to get the down or up state of the mouse are really appreciated.

Share Improve this question asked Apr 11, 2012 at 9:30 Shadrack OrinaShadrack Orina 7,9732 gold badges32 silver badges36 bronze badges 1
  • When drag & drop from external content, seems like the page gets activated only after DROP. – Selvakumar Arumugam Commented Jul 17, 2013 at 20:37
Add a ment  | 

4 Answers 4

Reset to default 3 +50

The issue as I understand it is that you need to determine whether the left mouse button is pressed if it was pressed outside of the window (for a dragging operation).

There are a number of issues:

  • there are no mousemove events fired during a dragging operation
  • data of current button states differs between browsers

I have e up with this solution:

/**
 * 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
}

The above solution binds to the mousemove event, and the dragover event. Chrome gets a valid event object with the correct button values in the dragover event, however I found that FireFox did not. I figure the state of the left mouse button is pretty obvious during a drag operation, it's going to be pressed, right? You can't drag without clicking and moving. So I just set state to 1 (left down) on dragover. Likewise, on dragleave, the value is set to zero.

You'd do all of the normal dragover, dragstart, end, drop, etc handling to prevent the default browser actions and the value returned by window.getButtonState() should always be the value of the currently active mouse button.

Here's some example usage that sets the value of the first h1 tag in the page to the currently pressed button:

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

})()

You'll have to do some tweaking cross browsers for handling the different values (FF reported 4 for the middle button, etc.) but you should be able to get the current button reasonably well with this method.

Try it out: http://jsfiddle/6BUA4/

When you select text in an external program(such as Word) and drag it onto a web page, elements on the page will generate dragenter Mouse events. I tested this in Chrome and it worked for me. For instance, I can bind a dragenter listener to document.body and receive the events even though no normal mouse events are fired:

function logEvent(e) {
    console.log(e);
}

document.body.addEventListener('dragenter', logEvent);

// MouseEvent {dataTransfer: Clipboard, toElement: body, ..., button: 0, ...}

Perhaps you can use this to your advantage, since the dragenter event means that the mouse is dragging and that the button must be pressed. In addition, you can get the text being dragged by getting the data from the event:

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

You need to use the correct data type in the getData call. I typed some text into Word and was able to get that dragged text with text/plain.

Have a variable with the state: Demo - Code

var _isMouseDown = false;

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

Then you can check _isMouseDown to see if mouse is down.

Or more pact: Demo - Code

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

If you don't want global variables you can save _isMouseDown throw jQuery's data method: Demo - Code

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

And check throw: $(document).data("_isMouseDown")


You're looking for new robust HTML5 drag and drop http://www.w3schools./html/html5_draganddrop.asp

The event you're looking for is "drop"

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

Of course you should move this code into js file, but this gives you example what has been done. You may want to read what's inside that outside drop, even use it for uploads.

Here is detailed info about event.dataTransfer http://www.tutorialspoint./html5/html5_drag_drop.htm

发布评论

评论列表(0)

  1. 暂无评论