問題描述
我希望能夠在帶有文件的光標進入瀏覽器窗口后立即突出顯示放置區域,這與 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
.然后設置一個短暫的超時來檢查標志是否仍然為假. - 理想情況下,在設置下一個超時之前跟蹤并清除它.
- Set a flag (
showDrag
) totrue
ondragenter
anddragover
of the html (or body) element. - On
dragleave
set the flag tofalse
. 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.
這篇關于如何像 Gmail 一樣檢測進入和離開窗口的 HTML5 拖動事件?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!