开发者

'onmousedrag' event js

I have some code that works each time onmouseclick and continuously onmousemove when I set them accordingly. I am looking for a way to combine the two (i.e. like a click and drag) which I thought would be a simple task but cannot find any simple explanation. The closest I get is drag-and-drop tutorials.

Do I have to call t开发者_运维百科he onmousemove event while the onmouseclick event is triggered? Or is there something really simple I am completely overlooking?


You might want to just use a flag like this: http://jsfiddle.net/n3MeH/.

var isMouseDown = false;
document.onmousedown = function() { isMouseDown = true  };
document.onmouseup   = function() { isMouseDown = false };
document.onmousemove = function() { if(isMouseDown) { /* do drag things */ } };


You could try something like this:

var div = document.getElementById('ex');

div.onmousedown = function(){
    document.onmousemove = function(e){
        div.innerText = '('+e.pageX +', '+e.pageY+')';
    }
    document.onmouseup = function(e){
        div.innerText = 'Click Me!';
        document.onmousemove = function(){};
    }
}

It binds the documents mousemove and mouseup event on the divs mousedown.

http://jsfiddle.net/Paulpro/cSKq2/


If you don't want to use global variable for dragging, you can use event.buttons for determining which mouse button is pressed.

I tested this code in Chrome and Firefox.

document.onmousemove = function(event) {
    if(event.buttons == 1) { //dragged with left mouse button
        //your code
    }

    if(event.buttons > 0) { //dragged with any mouse button
        //your code
    }
}


really simple... I hope :)

when the mousedown event is triggered, set a global "dragging" variable to true. Then when mouseup is triggered, set it to false.


if I'm understanding correctly I think you just want to break your onmouseclick into onmousedown and onmouseup (like setting a draggable bool, and then revert it on mouse up...but since you said the closest you found is drag/drop info, maybe you mean something else?)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜