<input type="file"> 是出了名的難客製:它的「選擇檔案」按鈕由瀏覽器繪製,無法用 CSS 直接改樣式。常見的解法有個漂亮的名字叫「透明替身法」——讓真正的 file 元件透明地蓋在自訂按鈕上,使用者點到的其實還是原生元件。
<body>
<input type="file" id="j" onchange="getValue();"
style="-moz-opacity:0;filter:alpha(opacity=0);opacity:0;position:absolute;left:166px;" />
<input id="ye" style="color: green;border: 1px solid green;width:300px;" />
<input type="button" value="File" style="border: 1px solid green;width:80px;" />
</body>
<script language="javascript">
function getValue(){
document.getElementById('ye').value = document.getElementById('j').value;
}
</script>
1. 把原生的 file 元件透明化:-moz-opacity:0 給舊 Firefox、filter:alpha(opacity=0) 給舊 IE、opacity:0 給標準瀏覽器,三寫是為了跨瀏覽器。
2. 用自己的元件重畫外觀:一個 text input 顯示檔名,一個 button 當作視覺上的「選擇檔案」。
3. 把透明的 file 元件疊在自訂按鈕上方:用 position:absolute 搭配 left 值對齊,使用者點下去時,滑鼠其實落在原生 file 元件上,於是照樣開啟檔案選擇對話框。
4. 用 JS 同步顯示路徑:onchange 觸發 getValue(),把 file 元件的值複製到文字框。
這個做法的優點是:真正處理上傳的仍然是原生 file 元件,表單提交流程完全不變,只是外觀換成我們自己畫的。
· 路徑顯示會因瀏覽器而異。基於安全考量,IE 會回傳完整本機路徑(C:\folder\a.jpg),Firefox 與 Chrome 只回傳檔名(a.jpg)。因此這個方法在不同瀏覽器上顯示的內容長度可能不同,若要一致,建議自行只取檔名(參考 ID 11250 的做法)。
· 文字框應該設為 readonly。否則使用者可以手動打字進去,造成畫面顯示的與實際要上傳的檔案不一致,容易誤導。
今天不需要透明度 hack 了,直接用 <label> 綁定即可:
<label class="upload-btn">
選擇檔案
<input type="file" onchange="showName(this)">
</label>
<span id="fname">未選擇檔案</span>
<style>
.upload-btn{
display:inline-block; padding:6px 18px;
background:#2d7; color:#fff; border-radius:4px; cursor:pointer;
}
.upload-btn input{ display:none; } /* 隱藏原生元件,但 label 仍可觸發它 */
</style>
<script>
function showName(input){
document.getElementById('fname').textContent =
input.files.length ? input.files[0].name : '未選擇檔案';
}
</script>
<label> 包著 <input> 時,點擊 label 等同點擊 input,完全不需要 JavaScript 幫忙定位,也不必處理透明度相容問題。而且用 input.files[0].name 取檔名,天生就是純檔名,不會有路徑差異的困擾。