When I first started, I found an example on the Internet. This example mentioned that drag-related events need to be blocked on the document. The default processing method for all events, the code is as follows:
$(document).on({ dragleave:function(e){ //拖离 e.preventDefault(); }, drop:function(e){ //拖后放 e.preventDefault(); }, dragenter:function(e){ //拖进 e.preventDefault(); }, dragover:function(e){ //拖来拖去 e.preventDefault(); } });
In fact, in our file upload, the area that accepts drag and drop is generally only a small area, so I simplified it as follows
$drop.on("dragenter", function (e) { e.preventDefault(); console.log("enter"); $drop.addClass("hover");});$drop.on("dragleave drop", function (e) { e.preventDefault(); console.log("leave"); $drop.removeClass("hover");});$drop.on("dragover", function (e) { e.preventDefault();})
Moreover, during the enter event, a hover style is added to the target area to highlight the accepting area
The default is Jiang purple (So this style should be removed in the drop and leave events)
because they need to be processed at the same time input box and drag area, so my html structure is as follows:
{{msg}}
is the drop event of#dropBox
andinput
The change event is also bound to theChange
function and the event object is passed into the function
Here, I added theprevent
modifier to thedrop
event. Shield the default event. If the event is not blocked, the accepting area#dropBox
will not be able to receive the file, and the file will trigger the browser to download (if it cannot be previewed directly) or preview;
Change:function(ev){ var e = window.event || ev; var file = e.target.files ? e.target.files[0] : e.dataTransfer.files[0]; if(!file){ vm.msg = "点击选择,或者拖拽填写好数据的excel文件致此"; vm.isError = true; return false } },
ps: The business logic in the js code is hidden and only the public part is described.
When accepting files selected by the user, usee.target.files
As a judgment condition, to determine whether there is a file selected by input, if so, takee.target.files[0]
, if not, takee.dataTransfer.files[0]
.
The properties of these two event objects are hung on the event object by the browser according to different situations.
The above is the detailed content of How to implement file drag and drop upload. For more information, please follow other related articles on the PHP Chinese website!