简体   繁体   English

在javascript / jquery中取消事件mousedown

[英]cancel event mousedown in javascript / jquery

I'm doing a drag and drop and when the draggable object passes certain limits that I have set to the screen I want to return it to its original position. 我正在执行拖放操作,当可拖动对象超过我已设置到屏幕的某些限制时,我想将其返回到其原始位置。

My problem is that if the onmousedown event is active the object don't return to its original position until onmouseup event is called. 我的问题是,如果onmousedown事件处于活动状态,则在调用onmouseup事件之前,该对象不会返回其原始位置。

Is it possible to cancel or stop mousedown while it's running? 运行时是否可以取消或停止mousedown?

You can clear the mousemove event when a specific condition is met: 满足特定条件时,可以清除mousemove事件:

function trackMouse(e) {
    if (e.pageX > 200 || e.pageY > 200) {
        // stop execution (event continues to run)
        // alternatively, to detach this event:
        $(window).off('mousemove', trackMouse);
    } else {
        $('#output').html(e.pageX +', '+ e.pageY); 
    }
}

$(window).on('mousemove', trackMouse);​

Demo (JSLint) 演示(JSLint)

Sounds like you should be using the onmousemove-event to see if you've reached the limit, but are using the onmousedown, which as you say won't fire before you release the mouse button. 听起来您应该使用onmousemove-event来查看您是否已达到限制,但正在使用onmousedown, 正如您所说的,在释放鼠标按钮之前不会触发。 which is is fired only once as you press the mousebutton 按下鼠标按钮时仅触发一次

Perhaps you may find this jquery.event.drag plugin useful. 也许您会发现此jquery.event.drag插件有用。 It allows you to cancel the drag while it is in progress. 它允许您取消正在进行的拖动。 From its docs: 从其文档:

drag 拖动

This event fires after "draginit" and "dragstart" every time the mouse moves. 每次鼠标移动时,都会在“ draginit”和“ dragstart”之后触发此事件。 The handler can return false to stop the drag interaction and go straight to "dragend" and also prevent any "drop" events. 处理程序可以返回false来停止拖动交互,并直接进入“拖动”状态,还可以防止任何“放置”事件。 If dragging multiple elements (from "draginit"), this event will fire uniquely on each element. 如果拖动多个元素(从“ draginit”拖动),则此事件将在每个元素上唯一触发。

@Voitek Zylinski: your solution works, but I finally found this solution that is better in my case: @Voitek Zylinski:您的解决方案有效,但我最终发现此解决方案对我而言更好:

$(document).trigger("mouseup");

Thank you. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM