问题描述

Possible Duplicate:
In JavaScript can I make a “click” event fire programmatically for a file input element?

我有一个看起来像这样的网页

<html>
    <head>
        <title>File Upload Click Test</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    </head>
    <body>
        <div onclick="$('input[type=file]').click()" >CLICK SIMULATOR</div>
        <input type="file"></input>
    </body>
</html>

我的目标是让 div 在文件输入中提出点击事件,这似乎与 IE 和 Chrome 中的预期一样,但在 Firefox 中不起作用 (当您点击文件浏览器时,不会打开文件浏览器 DIV) 。

有没有办法让这个工作在 FF?

最佳解决办法

Is there a way to get this working in FF?

不,也可以在大多数常见版本的 IE 中运行。 IE 将打开该对话框,但一旦您选择了一个文件,表单将不会实际提交。

放弃希望伪造文件上传框的唯一方法是使用透明度技术,因为浏览器可能会在内部设置不同的文件上传框 (甚至提供不包括浏览对话框的文件上传控件),这是真的不推荐的,因此很可能最终会导致无法使用的形式。

学习爱上灰色文件上传字段,或使用渐进增强功能将其替换为可用的 Flash 。

次佳解决办法

以下是解决方法 (FF) 。 HTML 位:

<label>Upload Business Logo</label>
<input type="file" name="logo" id="logo" class="file-upload" />
<input type="text" id="text-logo" class="text-upload" readonly/>
<input type="button" id="btn-logo" class="btn-upload" alt="" />

CSS 的输入文件类型:

.file-upload { display:none; }

jQuery 位:

//bind click
$('#btn-logo').click(function(event) {
  $('#logo').click();
});

//capture selected filename
$('#logo').change(function(click) {
  $('#text-logo').val(this.value);
});

表单提交后,隐藏的输入文件将上传文件。希望这可以帮助 :)

参考文献

注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛