HTML5 Drag Release offsetX offsetY jump

后端 未结 5 482
暖寄归人
暖寄归人 2021-01-02 07:19

I\'m playing with the HTML5 drag and drop and tracking the mouse position while dragging.

OffsetX and OffsetY works awesome until you release the mouse, the offsets

5条回答
  •  伪装坚强ぢ
    2021-01-02 07:58

    I had the same problem and came up with a solution that will work 99.99999% of the time. the explanation is below:

    Solution (should work in every case your users will run into)

    eng.window.addEventListener(
        "drag"
        ,function(event){
            //If both screenX and screenY are 0, likely the user just released.
            if(!event.screenX && !event.screenY) return;
            
            //Your code here
        }
    );
    

    Explanation

    I looked through the event returned on releasing the mouse and compared it to the event immediately before, and couldn't find anything that will work in 100% of the cases- there's no easy "buttonPressed" feature or the like hidden inside the object.

    I did see though that every single measure of cursor position is changed when you release: clientX, layerX, offsetX, pageX, screenX, and regular x/y. They all default to the top-left value possible, which may be the top-left corner of the window- or the screen.

    But what is the likelihood that your user will go into fullscreen mode drag and drop an element into the very top-left pixel of their screen? (In Chrome for me, screenX is actually set to the left edge of the window; but screenY takes Chrome's HUD into account)

    So while the above won't work in that 1 fringe case (that your users will likely never-ever run into), it will work every other time.

    Tested in Chrome.

提交回复
热议问题