简体   繁体   English

触发掉落事件

[英]Trigger drop event

I have a form with an input type="file" . 我有一个input type="file"的表单。 I have a div surrounding the input . 我在input周围有一个div I then set the input to display:none . 然后,将input设置为display:none In JavaScript, I set that when you select the div , the input gets selected. 在JavaScript中,我设置为在选择div时选择input

That all works nice and dandy, but how can I make it that when you drag a file onto the div , the input should trigger a drop event? 一切都很好,但当我将文件拖到div ,如何使input触发drop事件呢?

So here's how I would do the click event: 因此,这就是我要做click事件的方式:

$('#target').click();

I'm looking for something like this: 我正在寻找这样的东西:

$('#target').drop();

JSFiddle 的jsfiddle

 $(document).ready(function() { $('#browseFileDiv').click(function(e) { $(this).find('input[type="file"]').click(); }); $('#browseFileDiv input').click(function(e) { e.stopPropagation(); }); }); 
 #browseFileDiv { height: 200px; width: 200px; background-color: orange; border-radius: 50%; } #browseFileDiv > input { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form action="upload.php" enctype="multipart/form-data" method="POST" id="uploadform"> <div id="browseFileDiv"> <input id="openFile" name="img" type="file" /> </div> </form> 

$('#browseFileDiv').on('drop', function(){/* code here */}) is probably what you're looking for. $('#browseFileDiv').on('drop', function(){/* code here */})可能就是您想要的。

You probably really want to use jQuery UI . 您可能真的想使用jQuery UI Click the view source button. 单击view source按钮。

First, you don't need to wrap the <input type="file"> with a div around it and then with javscript trigger the .click() event for that input file if you click the div, make a <label> for this input file and style it, thus you can trigger the click event with HTML only without the need for javascript: 首先,您不需要在<input type="file">周围加上div,然后用javscript触发该输入文件的.click()事件.click()如果您单击div),则为<label> input <label>此输入文件并设置其样式,因此您可以仅使用HTML触发click事件,而无需使用javascript:

<label for="openFile" id="browseFile"></label>
<input id="openFile" name="img" type="file">

Updated: Then, as in this JS Fiddle the problem is that you need to return false; 更新:然后,就像在JS Fiddle中一样 ,问题是您需要return false; for the ondragover and ondrop events 用于ondragoverondrop事件

var browseFile = document.getElementById('browseFile');
browseFile.ondragover = function () {
    return false;
};
browseFile.ondrop = function (event) {
    event.preventDefault && event.preventDefault();
    var files = event.dataTransfer.files;
    console.log(files);
    return false;
};

** Note that the above works for multiple files as well. ** 请注意,以上内容也适用于多个文件。

Resource: http://html5doctor.com/drag-and-drop-to-server/ 资源: http//html5doctor.com/drag-and-drop-to-server/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM