我想通过编程方式在<input type="file">标记上生成一个点击事件。

仅仅调用click()似乎没有做任何事情,或者至少它不会弹出一个文件选择对话框。

我一直在尝试使用侦听器捕获事件并重定向事件,但我还不能像某人点击它那样实际执行事件。


当前回答

我发现如果输入(文件)是外部形式,那么触发单击事件调用文件对话框。

其他回答

这将在Firefox 4中实现,但需要注意的是,它被视为一个弹出窗口,因此无论何时弹出窗口都将被阻止。

要做到这一点,你可以点击文件输入上的一个不可见的传递元素:

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)
}

你不能在所有浏览器中都这么做,IE应该允许,但Mozilla和Opera不允许。

当您在GMail中撰写消息时,“附加文件”功能以一种方式为IE和任何支持此功能的浏览器实现,然后以另一种方式为Firefox和那些不支持此功能的浏览器实现。

我不知道为什么你不能这样做,但有一件事是有安全风险的,而且你不允许在任何浏览器中这样做,那就是在HTML file元素上以编程方式设置文件名。

以下是对我有用的解决方案: CSS:

#uploadtruefield {
    left: 225px;
    opacity: 0;
    position: absolute;
    right: 0;
    top: 266px;
    opacity:0;
    -moz-opacity:0;
    filter:alpha(opacity:0);
    width: 270px;
    z-index: 2;
}

.uploadmask {
    background:url(../img/browse.gif) no-repeat 100% 50%;
}
#uploadmaskfield{
    width:132px;
}

HTML与“小”JQuery帮助:

<div class="uploadmask">
    <input id="uploadmaskfield" type="text" name="uploadmaskfield">
</div>
<input id="uploadtruefield"  type="file" onchange="$('#uploadmaskfield').val(this.value)" >

只是要确保maskfied被true upload字段完全覆盖。

我一整天都在寻找解决办法。以下是我得出的结论:

出于安全原因,Opera和Firefox不允许触发文件输入。 唯一方便的选择是创建一个“隐藏”文件输入(使用不透明,而不是“隐藏”或“显示:none”!),然后在它下面创建按钮。通过这种方式,按钮是可见的,但用户单击它实际上激活了文件输入。 上传文件