萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> 互動設計

Web 實現點擊圖片彈出上傳檔案視窗:純 CSS + HTML 方案

透過簡單代碼即可實現點擊圖片彈出上傳檔案視窗,省去 <input type="file"> 原生樣式難美化的問題。具體實現如下:

核心原理

建立一個容器顯示自訂圖片,內部疊加一個 opacity: 0 的 <input type="file">,覆蓋整個容器區域。使用者點擊圖片實際觸發透明輸入框,喚起原生檔案選擇對話框。

完整代碼

<style>
.fileInputContainer {
  height: 256px;
  background: url(upfile.png);
  position: relative;
  width: 256px;
}
.fileInput {
  height: 256px;
  overflow: hidden;
  font-size: 300px; /* 讓輸入框足夠大覆蓋整個區域 */
  position: absolute;
  right: 0;
  top: 0;
  opacity: 0;
  filter: alpha(opacity=0); /* IE8 相容 */
  cursor: pointer;
}
</style>

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

關鍵點:font-size: 300px 讓透明輸入框點擊區域足夠大;position: absolute 疊加於自訂圖片上方;opacity: 0 隱藏原生醜陋樣式。此法相容性好、無需 JavaScript、易於樣式客製化。

copyright © 萬盛學電腦網 all rights reserved