DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> WEB網站前端 >> 前端技巧
點擊圖片開啟檔案選擇視窗的上傳元件做法
編輯:前端技巧     

原生的 <input type="file"> 外觀由各瀏覽器決定,很難與設計稿一致。常見的解法是把真正的 file input 透明化,疊在一張圖片上方——使用者看到的是美觀的圖片,點下去觸發的仍是原生檔案選擇器。

完整程式碼

<style>
.fileInputContainer {
  height: 256px;
  width: 256px;
  background: url(upfile.png);
  position: relative;
}
.fileInput {
  height: 256px;
  overflow: hidden;
  font-size: 300px;
  position: absolute;
  right: 0;
  top: 0;
  opacity: 0;
  filter: alpha(opacity=0);
  cursor: pointer;
}
</style>

<div class="fileInputContainer">
  <input class="fileInput" type="file" name="" id="" />
</div>

逐項解析

  • 容器設為 relative:作為定位參照,讓 input 能準確疊在圖片上。
  • input 設為 absolute 並貼齊右上角:確保透明元件完整覆蓋圖片區域。
  • opacity: 0 與 filter: alpha(opacity=0):前者給現代瀏覽器,後者給 IE8 以下。兩者並用是為了讓 input 完全透明但仍可互動。
  • font-size: 300px:這是個關鍵技巧。瀏覽器的檔案選擇按鈕尺寸會隨字級放大,把 font-size 設得很大能確保這個按鈕撐滿整個 input 區域,不會出現「只有右邊一小塊能點」的問題。
  • overflow: hidden:裁掉被撐大的按鈕溢出部分。
  • cursor: pointer:讓游標移入時變成手指,暗示這裡可以點。

為什麼不直接用 label

還有一個更簡潔的現代做法,不需要任何透明度 hack:

<style>
.fileInput { display: none; }
.uploadLabel {
  display: block;
  width: 256px;
  height: 256px;
  background: url(upfile.png);
  cursor: pointer;
}
</style>

<label class="uploadLabel" for="myFile"></label>
<input class="fileInput" type="file" id="myFile" />

用 label 的 for 屬性關聯到 file input,點擊 label 等同點擊 input。這個做法的好處是:HTML 語意清楚、不需要透明度與字級 hack、鍵盤操作(Tab 聚焦後按 Enter)也能正常運作,而上面那個透明疊加法的鍵盤 usability 其實是有問題的——使用者看不見焦點在哪。

若要進一步自訂「已選檔案名稱」的顯示,監聽 change 事件即可:

document.getElementById('myFile').addEventListener('change', function (e) {
  const name = e.target.files[0] ? e.target.files[0].name : '尚未選擇檔案';
  document.querySelector('.filename').textContent = name;
});
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved