'onmousedrag' event js

喜欢而已 提交于 2019-12-19 03:58:59

问题


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 the onmousemove event while the onmouseclick event is triggered? Or is there something really simple I am completely overlooking?


回答1:


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



回答2:


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/




回答3:


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



回答4:


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.




回答5:


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?)



来源:https://stackoverflow.com/questions/6819045/onmousedrag-event-js

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