想要讓一個連結文字點下去就跳出檔案選擇視窗,做法是:把真正的 input[type=file] 隱藏起來,再用 JavaScript 代為觸發它的點擊事件。
<div>
<a href="###">添加圖片</a>
<input type="file" name="image" class="hidden" value="" />
</div>
.hidden {
display: none;
}
$('a').on('click', function(e) {
e.preventDefault();
$(this).closest('input[type=file]').trigger('click');
})
三個環節缺一不可:e.preventDefault() 阻止 a 的預設跳轉,避免網址被改成「###」;closest() 往上找出同一層的 input;trigger('click') 才是真正把檔案對話框叫出來的關鍵。
要留意的是,這裡的選擇器寫成 $(this).closest('input[type=file]') 有個前提——input 必須是 a 的祖先元素。但範例結構中 a 與 input 是兄弟關係,closest 會找不到,實作時應改用 $(this).parent().find('input[type=file]') 或 $(this).siblings('input[type=file]')。
另外,基於安全性考量,瀏覽器只允許由使用者「真實點擊」觸發檔案對話框。因此這段程式必須綁在使用者互動事件上,若放在 onload 或 setTimeout 中呼叫,會被瀏覽器阻擋而無效。