我希望能够在带有文件的光标进入浏览器窗口后立即突出显示放置区域,这与 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.
我一直在尝试做这样的事情:
I keep trying to do something like this:
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.
我错过了什么?
我用超时解决了它(不是很干净,但可以):
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:
dragenter 和 html(或正文)的 dragover 上将标志 (showDrag) 设置为 true元素.dragleave 上将标志设置为 false.然后设置一个短暂的超时来检查标志是否仍然为假.showDrag) to true on dragenter and dragover of the html (or body) element.dragleave set the flag to false. Then set a brief timeout to check if the flag is still false.这样,每个 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.
这篇关于如何像 Gmail 一样检测进入和离开窗口的 HTML5 拖动事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何在 Jasmine 中编写 FileReader 测试?How do I write FileReader test in Jasmine?(如何在 Jasmine 中编写 FileReader 测试?)
JS/HTML5 WebSocket:无需 HTTP 调用即可连接JS/HTML5 WebSocket: Connect without HTTP call(JS/HTML5 WebSocket:无需 HTTP 调用即可连接)
CSS:分页后重复表头(打印视图)CSS: Repeat Table Header after Page Break (Print View)(CSS:分页后重复表头(打印视图))
将 HTML 头放在另一个文件中Put HTML head in another file(将 HTML 头放在另一个文件中)
“头"和“头"之间的真正区别是什么?和“What is the real difference between the quot;headquot; and quot;headerquot; tag?(“头和“头之间的真正区别是什么?和“标题标签?)
IE8 中具有 100% 内容高度的页眉/页脚布局Header/Footer Layout with 100% Content Height in IE8(IE8 中具有 100% 内容高度的页眉/页脚布局)