我想通过编程方式在<input type="file">标记上生成一个点击事件。
仅仅调用click()似乎没有做任何事情,或者至少它不会弹出一个文件选择对话框。
我一直在尝试使用侦听器捕获事件并重定向事件,但我还不能像某人点击它那样实际执行事件。
我想通过编程方式在<input type="file">标记上生成一个点击事件。
仅仅调用click()似乎没有做任何事情,或者至少它不会弹出一个文件选择对话框。
我一直在尝试使用侦听器捕获事件并重定向事件,但我还不能像某人点击它那样实际执行事件。
当前回答
我有一个<input type="button">标签隐藏在视图中。我所做的是将“onClick”事件附加到任何类型的可见组件(如标签)。这是使用谷歌Chrome的开发工具或Mozilla Firefox的Firebug使用右键单击“编辑HTML”命令完成的。在这种情况下,指定以下脚本或类似的东西:
如果你有JQuery:
$('#id_of_component').click();
如果不是:
document.getElementById('id_of_component').click();
谢谢。
其他回答
您可以在任何浏览器上触发click(),但有些浏览器需要元素是可见和聚焦的。下面是一个jQuery示例:
$('#input_element').show();
$('#input_element').focus();
$('#input_element').click();
$('#input_element').hide();
它与click()之前的隐藏一起工作,但我不知道它是否在不调用show方法的情况下工作。从来没有在Opera上尝试过,我在IE/FF/Safari/Chrome上测试过,它是有效的。我希望这能有所帮助。
要做到这一点,你可以点击文件输入上的一个不可见的传递元素:
function simulateFileClick() {
const div = document.createElement("div")
div.style.visibility = "hidden"
div.style.position = "absolute"
div.style.width = "100%"
div.style.height = "100%"
div.style.pointerEvents = "none"
const fileInput = document.getElementById("fileInput") // or whatever selector you like
fileInput.style.position = "relative"
fileInput.appendChild(div)
const mouseEvent = new MouseEvent("click")
div.dispatchEvent(mouseEvent)
}
您可以根据<a>标记上的“打开文件对话框”中的回答来执行此操作
<input type="file" id="upload" name="upload" style="visibility: hidden; width: 1px; height: 1px" multiple />
<a href="" onclick="document.getElementById('upload').click(); return false">Upload</a>
试试这个解决方案:http://code.google.com/p/upload-at-click/
对于那些知道你必须在链接上覆盖一个看不见的表单,但懒得写的人,我为你写了它。对我来说是,但还是分享吧。欢迎提出意见。
HTML(某处):
<a id="fileLink" href="javascript:fileBrowse();" onmouseover="fileMove();">File Browse</a>
HTML(你不关心的地方):
<div id="uploadForm" style="filter:alpha(opacity=0); opacity: 0.0; width: 300px; cursor: pointer;">
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" />
</form>
</div>
JavaScript:
function pageY(el) {
var ot = 0;
while (el && el.offsetParent != el) {
ot += el.offsetTop ? el.offsetTop : 0;
el = el.offsetParent;
}
return ot;
}
function pageX(el) {
var ol = 0;
while (el && el.offsetParent != el) {
ol += el.offsetLeft ? el.offsetLeft : 0;
el = el.offsetParent;
}
return ol;
}
function fileMove() {
if (navigator.appName == "Microsoft Internet Explorer") {
return; // Don't need to do this in IE.
}
var link = document.getElementById("fileLink");
var form = document.getElementById("uploadForm");
var x = pageX(link);
var y = pageY(link);
form.style.position = 'absolute';
form.style.left = x + 'px';
form.style.top = y + 'px';
}
function fileBrowse() {
// This works in IE only. Doesn't do jack in FF. :(
var browseField = document.getElementById("uploadForm").file;
browseField.click();
}