問題描述
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://googleajax.admincdn.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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。