基於安全性理由,<input type="file"> 的「瀏覽」按鈕外觀一直不聽話。在只能用表單 POST 上傳的舊瀏覽器環境裡, designer 的設計稿往往跟它格格不入。解法很巧妙:把真正的 file 控制項設為透明,蓋在自己畫的按鈕上。
兩個元素疊在一起:一個是自製的文字層(顯示「上傳」字樣),一個是透明但可互動的 file 控制項。旁邊再放一個文字框顯示選到的檔名。
<style>
#ui-upload-holder {
position: relative; width: 60px; height: 35px;
border: 1px solid silver; overflow: hidden;
}
/* 真正被點擊的 file 控制項:鋪滿容器且完全透明 */
#ui-upload-input {
position: absolute; top: 0; right: 0; height: 100%;
cursor: pointer;
opacity: 0; filter: alpha(opacity: 0);
z-index: 999;
}
/* 顯示用的文字層,墊在透明控制項下方 */
#ui-upload-txt {
position: absolute; top: 0; left: 0;
width: 100%; height: 100%;
line-height: 35px; text-align: center;
}
#ui-upload-filepath {
position: relative; border: 1px solid silver;
width: 150px; height: 35px; overflow: hidden; float: left;
}
#ui-upload-filepathtxt {
position: absolute; top: 0; left: 0;
width: 100%; height: 35px; border: 0; line-height: 35px;
}
</style>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" >
<title>upload...</title>
<style>
#ui-upload-holder { position:relative; width:60px; height:35px;
border:1px solid silver; overflow:hidden; }
#ui-upload-input { position:absolute; top:0; right:0; height:100%;
cursor:pointer; opacity:0; filter:alpha(opacity:0); z-index:999; }
#ui-upload-txt { position:absolute; top:0; left:0; width:100%; height:100%;
line-height:35px; text-align:center; }
#ui-upload-filepath { position:relative; border:1px solid silver;
width:150px; height:35px; overflow:hidden; float:left; }
#ui-upload-filepathtxt { position:absolute; top:0; left:0; width:100%;
height:35px; border:0; line-height:35px; }
.uploadlay { margin:200px; border:1px green solid;
width:300px; height:200px; padding:10px; }
</style>
</head>
<body>
<div class="uploadlay">
<div id="ui-upload-filepath">
<input type="text" id="ui-upload-filepathtxt" class="filepathtxt" />
</div>
<div id="ui-upload-holder">
<div id="ui-upload-txt">上傳</div>
<input type="file" id="ui-upload-input" name="myfile" />
</div>
</div>
<script>
document.getElementById("ui-upload-input").onchange = function () {
document.getElementById("ui-upload-filepathtxt").value = this.value;
};
</script>
</body>
</html>
cursor:pointer,左右兩側的游標會不一致。input.click() 雖然能彈出視窗,但選完的檔案無法被上傳。所以透明控制項必須覆在文字層上方,而不是反過來。target 指向 iframe 名稱)。這套技巧在 XHR Level 2 與 File API 普及後已無必要。現代瀏覽器都能用 FormData 直接非同步上傳,並在傳送前取得檔案名稱、大小與型別:
<label class="btn">
上傳
<input type="file" id="picker" hidden>
</label>
<script>
document.getElementById('picker').addEventListener('change', function () {
var file = this.files[0];
if (!file) return;
var fd = new FormData();
fd.append('myfile', file);
fetch('/upload', { method: 'POST', body: fd })
.then(function (r) { return r.json(); })
.then(function (data) { console.log('上傳完成', data); });
});
</script>
用 <label> 包住 hidden 的 file 輸入,點標籤就會開啟檔案選擇器,而且鍵盤操作與螢幕閱讀器都能正常運作——這比透明疊層更簡單,也更友善。若堅持要自訂外觀,記得幫自製按鈕加上 role="button" 與鍵盤回饋,別讓它變成只有滑鼠按得動的裝飾品。