如何检测HTML5拖动事件进入和离开窗口,像Gmail? [英] How do I detect a HTML5 drag event entering and leaving the window, like Gmail does?

查看:91
本文介绍了如何检测HTML5拖动事件进入和离开窗口,像Gmail?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在携带文件的光标进入浏览器窗口后立即突出显示放置区域,就像Gmail所做的一样。但是我不能让它工作,而且我觉得我只是错过了一些非常明显的东西。

I'd like to be able to highlight the drop area as soon as the cursor carrying a file enters the browser window, exactly the way Gmail does it. But I can't make it work, and I feel like I'm just missing something really obvious.

我一直在尝试这样做:

this.body = $('body').get(0)
this.body.addEventListener("dragenter", this.dragenter, true)
this.body.addEventListener("dragleave", this.dragleave, true)`

但是,只要光标移过BODY以外的元素,它就会触发事件,这是有道理的,但绝对不起作用。我可以把一个元素放在一切的顶部,覆盖整个窗口并检测出来,但这将是一个可怕的方式。

But that fires the events whenever the cursor moves over and out of elements other than BODY, which makes sense, but absolutely doesn't work. I could place an element on top of everything, covering the entire window and detect on that, but that'd be a horrible way to go about it.

我是什么缺少?

推荐答案

我用超时(不是squeaky-clean,but works)解决了这个问题:

I solved it with a timeout (not squeaky-clean, but works):

var dropTarget = $('.dropTarget'),
    html = $('html'),
    showDrag = false,
    timeout = -1;

html.bind('dragenter', function () {
    dropTarget.addClass('dragging');
    showDrag = true; 
});
html.bind('dragover', function(){
    showDrag = true; 
});
html.bind('dragleave', function (e) {
    showDrag = false; 
    clearTimeout( timeout );
    timeout = setTimeout( function(){
        if( !showDrag ){ dropTarget.removeClass('dragging'); }
    }, 200 );
});

我的示例使用jQuery,但没有必要。以下是发生的情况的摘要:

My example uses jQuery, but it's not necessary. Here's a summary of what's going on:


  • 将标志( showDrag )设置为在 dragenter true 和html(或正文)的 dragover )元素

  • dragleave 将标志设置为 false 。然后设置一个短暂的超时时间来检查该标志是否仍然为false。

  • 理想情况下,请记住超时时间,然后再设置下一个。

  • Set a flag (showDrag) to true on dragenter and dragover of the html (or body) element.
  • On dragleave set the flag to false. Then set a brief timeout to check if the flag is still false.
  • Ideally, keep track of the timeout and clear it before setting the next one.

这样,每个 dragleave 事件给DOM足够的时间新的 dragover 事件来重置标志。我们关心的真实最终 dragleave 将会看到该标志仍然是假的。

This way, each dragleave event gives the DOM enough time for a new dragover event to reset the flag. The real, final dragleave that we care about will see that the flag is still false.

这篇关于如何检测HTML5拖动事件进入和离开窗口,像Gmail?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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