'onmousedrag' event js

前端 未结 5 930
情深已故
情深已故 2020-12-18 11:24

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

相关标签:
5条回答
  • 2020-12-18 11:36

    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 讨论(0)
  • 2020-12-18 11:42

    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/

    0 讨论(0)
  • 2020-12-18 11:45

    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
        }
    }
    
    0 讨论(0)
  • 2020-12-18 11:52

    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 */ } };
    
    0 讨论(0)
  • 2020-12-18 11:54

    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.

    0 讨论(0)
提交回复
热议问题