文件上傳是開發中不可或缺的功能。<input type="file" /> 雖是標準標籤,但它外型醜、又無法改「瀏覽」字樣。實務上我們常把它隱藏起來,改點擊其他元素(如圖片)來觸發選擇文件。本文完整示範這個做法並解決相容問題。
<style type="text/css">
._box {
width: 119px; height: 37px;
background-color: #53AD3F;
background-image: url(images/bg.png);
line-height: 37px; text-align: center;
color: white; cursor: pointer;
}
.none { width: 0px; height: 0px; display: none; }
</style>
<form id="form1" method="post" enctype="multipart/form-data">
<div class="_box">選擇圖片</div>
<div class="none">
<input type="file" name="_f" id="_f" />
</div>
</form>
<script>
jQuery(function () {
$("._box").click(function () { $("#_f").click(); });
});
</script>
但這個做法在部分舊版瀏覽器中,後台會抓不到 Request.Files。有人建議在 click 前加上 return:
$("._box").click(function () { return $("#_f").click(); });
加 return 後相容性提升不少,但仍有瀏覽器不買單。我們發現,只有「使用者手動點擊」file 輸入,後台才一定能拿到檔案。
於是把 <input type="file" /> 設為透明,蓋在可見的按鈕上方,讓使用者點到的其實就是 file 本身:
<style type="text/css">
._box {
position: relative;
width: 119px; height: 37px;
background-color: #53AD3F;
background-image: url(images/bg.png);
line-height: 37px; text-align: center;
color: white; cursor: pointer;
overflow: hidden;
z-index: 1;
}
._box input {
position: absolute;
width: 119px; height: 40px;
line-height: 40px; font-size: 23px;
opacity: 0;
filter: alpha(opacity=0);
left: -5px; top: -2px;
cursor: pointer;
z-index: 2;
}
</style>
<div class="_box">
<input type="file" name="_f" id="_f" />
選擇圖片
</div>
這個方案的精髓是:把一個不透明度為 0 的 file 輸入蓋在使用者可見的標籤或圖片上,讓使用者點擊時,實際點到的是那個透明的 file 輸入,因此後台必定拿得到檔案。其中,用 width、height、line-height、font-size 控制右側「瀏覽」按鈕的大小,用 left、top(可為負值)調整其位置,再用 z-index 管理層疊關係。最後別忘了,form 必須加上 enctype="multipart/form-data" 才能真正上傳檔案。如此一來,既美觀又能相容各瀏覽器,是相當實用的技巧。