DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML和Xhtml
自訂表單檔案選擇框樣式的完整實作
編輯:HTML和Xhtml     

原生 <input type="file"> 的外觀幾乎無法更動,跟任何設計稿放在一起都顯得突兀。實務上最乾淨的解法不是去「美化」它,而是讓真正的 file input 隱形,鋪在外層之上,把視覺交給自己寫的 div 與文字欄。

核心三層結構

<div class="uploader white">
  <input type="text" class="filename" readonly="readonly">  <!-- 顯示檔名 -->
  <input type="button" class="button" value="Browse...">     <!-- 裝飾用按鈕 -->
  <input type="file" size="30">                             <!-- 真正接收點擊 -->
</div>

關鍵樣式

外層容器負責裁切與圓角陰影:

.uploader{
  position:relative;
  display:inline-block;
  overflow:hidden;
  cursor:default;
  padding:0;
  margin:10px 0px;
  box-shadow:0px 0px 5px #ddd;
  border-radius:5px;
}

真正的 file input 被設為全透明並鋪滿整個容器,使用者點到的其實是它:

.uploader input[type=file]{
  position:absolute;
  top:0; right:0; bottom:0;
  border:0;
  padding:0; margin:0;
  height:30px;
  cursor:pointer;
  filter:alpha(opacity=0);
  opacity:0;
}

檔名欄做成左側圓角、單行省略,避免長檔名撐開版面:

.filename{
  float:left;
  display:inline-block;
  height:32px;
  width:180px;
  padding:8px 10px;
  overflow:hidden;
  border:1px solid #ccc;
  border-right:0;
  font:9pt/100% Arial, Helvetica, sans-serif;
  color:#777;
  text-overflow:ellipsis;
  white-space:nowrap;
  border-radius:5px 0px 0px 5px;
  background:#f5f5f5;
  box-sizing:border-box;
}

右側按鈕則是純裝飾,用 border-radius:0px 5px 5px 0px 補上右半圓角,並以漸層背景做出立體感。

用 jQuery 同步檔名

因為真正的 file input 是透明的,選檔後要記得把路徑寫回左側的 text 欄:

$(function(){
  $("input[type=file]").change(function(){
    $(this).parents(".uploader").find(".filename").val($(this).val());
  });
  $("input[type=file]").each(function(){
    if($(this).val()==""){
      $(this).parents(".uploader").find(".filename").val("No file selected...");
    }
  });
});

多套配色

原始範例另外提供了 white、blue、green、red、orange、black 六種配色,做法一致:只改寫 .button 的文字色、文字陰影、漸層起訖色與邊框色,並在 :hover 時把漸層方向反過來,就能做出按下時的明暗變化。需要的時候只要在外層加上對應的 class(例如 class="uploader blue")即可套用。

小結

這個模式的三個要點是:容器 position:relative + overflow:hidden、file input 絕對定位鋪滿且 opacity:0、檔名欄 readonly 由 JS 回填。理解之後,要換成任何設計風格都只需要改 CSS,不必再碰 HTML 結構。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved