原生拖动事件后如何获取mouseup事件? [英] How to get mouseup event after native drag event?

查看:100
本文介绍了原生拖动事件后如何获取mouseup事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

WHATWG 拖放的实现支持 dragstart drag dragend 事件。

The implementation of the WHATWG drag and drop supports dragstart, drag and dragend events.

当可拖动对象返回原始位置时,会触发 dragend 事件。尝试将红色框尽可能地拖动并释放。 拖动(和 END! console.log 消息)将不会触发,直到可拖动元素返回原始位置位置(在Safari浏览器中最明显)。

The dragend event fires when the draggable object returns to the original position, e.g. try dragging the red box as far as you can and release it. The dragend (and "END!" console.log message) will not fire until the draggable element returns to the original position (this is most visible in the Safari browser).

var handle = document.querySelector('#handle');

handle.addEventListener('dragend', function () {
    console.log('END!');
});

#handle {
    background: #f00; width: 100px; height: 100px;
}

<div id="handle" draggable="true"></div>

如何捕获 mouseup 或任何其他指示拖动手柄释放而没有延迟的事件?

How do I capture the mouseup or whatever else event that would indicate the release of the drag handle without a delay?

我尝试了以下变化:

var handle = document.querySelector('#handle');

handle.addEventListener('dragend', function () {
    console.log('END!');
});

handle.addEventListener('mouseup', function () {
    console.log('Mouseup');
});

#handle {
    background: #f00; width: 100px; height: 100px;
}

<div id="handle" draggable="true"></div>

虽然, mouseup在 dragstart 之后不会触发。

Though, "mouseup" does not fire after dragstart.

我最接近找到一个会触发的事件 mousemove

The closest I got to finding an event that would fire instantly after the release of the handle is mousemove:

var handle = document.querySelector('#handle');

handle.addEventListener('dragend', function () {
    console.log('END!');
});

window.addEventListener('mousemove', function () {
   console.log('I will not fire during the drag event. I will fire after handle has been released and mouse is moved.'); 
});

#handle {
    background: #f00; width: 100px; height: 100px;
}

<div id="handle" draggable="true"></div>

问题是这种方法需要用户移动鼠标。

The problem is that this approach requires user to move the mouse.

推荐答案

解决方法是启用 document.body

// @see https://developer.mozilla.org/en-US/docs/Web/Events/dragover
document.body.addEventListener('dragover', function (e) {
    // Prevent default to allow drop.
    e.preventDefault();
});

document.body.addEventListener('drop', function (e) {
    // Prevent open as a link for some elements.
    e.preventDefault();
});

制作 document.body 来收听 drop 事件导致 dragend 事件,认为您将在释放手柄时将元素移动到新位置。因此,句柄释放和 dragend 之间没有延迟。

Making document.body to listen for the drop event results in dragend thinking that you will move the element to the new position upon releasing the handle. Therefore, there is no delay between handle release and dragend.

这篇关于原生拖动事件后如何获取mouseup事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆