Javascript 触发点击输入文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25886480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
trigger click on input file
提问by Dariel Pratama
i have this mark up
我有这个标记
<div id="wrapper">
<input type="file" id="file" accept="image/*" capture="camera">
<a href="#" id="capture">Submit Cleanup</a>
</div>
and jQuery as follow
和 jQuery 如下
jQuery(function($){
$('#capture').on('click', function(e){
e.preventDefault();
$('#file').trigger('click');
});
});
the script works as expected on PC browser, but when i try on mobile device the camera doesnt prompt. also i already tried using click(), but same result.
该脚本在 PC 浏览器上按预期工作,但是当我在移动设备上尝试时,相机没有提示。我也已经尝试使用click(),但结果相同。
what could be the problem?
可能是什么问题呢?
回答by SSA
It's a security feature. Some browser doesn't allow a manual click on input type file. You can read more about hereand herealso.
这是一个安全功能。某些浏览器不允许手动单击输入类型文件。您也可以阅读更多关于这里和这里的信息。
Why isn't it possible to programmatically trigger the file input selection?
为什么不能以编程方式触发文件输入选择?
Most browsers prevent submitting files when the input field didn't receive a direct click (or keyboard) event as a security precaution. Some browsers (e.g. Google Chrome) simply prevent the click event, while e.g. Internet Explorer doesn't submit any files that have been selected by a programmatically triggered file input field. Firefox 4 (and later) is so far the only browser with full support for invoking "click"-Events on a completely hidden (display: none) file input field.
作为安全预防措施,当输入字段没有收到直接点击(或键盘)事件时,大多数浏览器会阻止提交文件。某些浏览器(例如 Google Chrome)只是阻止单击事件,而例如 Internet Explorer 不会提交任何已由以编程方式触发的文件输入字段选择的文件。Firefox 4(及更高版本)是迄今为止唯一完全支持在完全隐藏(显示:无)文件输入字段上调用“单击”事件的浏览器。
回答by Arun P Johny
In most browsers(
在大多数浏览器中(
jQuery(function($){
$('#capture').on('click', function(e){
e.preventDefault();
$('#file')[0].click();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="wrapper">
<input type="file" id="file" accept="image/*" capture="camera">
<a href="#" id="capture">Submit Cleanup</a>
</div>
回答by SynCap
<label>
<input type="file" name="myfile" accept="application/pdf" id="myfile" style="display:none">
CLICK HERE!
</label>
<br>
<a href="javascript:document.querySelector('input#myfile').click()">OR HERE</a>

