DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
用 CSS 加少量 JS 自訂檔案上傳按鈕的樣式
編輯:CSS詳解     

檔案上傳的 <input type="file"> 天生長得醜,而且各瀏覽器樣式不一,幾乎無法用 CSS 直接美化。常見的解法是把真正的 file input 透明化疊在自訂按鈕上,讓使用者點到的其實是原生控制項,但看到的是你自己畫的樣式。以下是一份完整可運行的範例,並在 Firefox 上驗證過。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"https://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=gb2312" />
<meta http-equiv="content-language" content="zh-cn" />
<meta name="keywords" content="關鍵字描述" />
<meta name="description" content="站點描述" />
<link rel="stylesheet" type="text/css" title="通用樣式" href="***.css" />
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
<title>css+js 定義 input 的 file 瀏覽按鈕樣式(相容 FireFox)</title>
<style type="text/css">
<!--
* { margin: 0; padding: 0; border: 0; }
body {
  font: 12px/130% verdana, geneva, arial, helvetica, sans-serif, 宋體;
  padding: 20px;
}
li { list-style: none; }
.clearfix:after {
  content: "&nbsp;";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
.clearfix { *display: inline-block; }
a:link, a:visited, a:hover { color: #000; text-decoration: none; }

.text {
  border: 1px solid #999;
  height: 16px;
  width: 300px;
  font-family: verdana;
  font-size: 12px;
  padding-top: 2px;
  float: left;
  margin-right: 5px;
}
.file {
  width: 64px;
  background: url(/img/ll.png);
  height: 20px;
  *vertical-align: 3px;
  overflow: hidden;
  float: left;
}
#file {
  width: 0;
  height: 20px;
  margin-left: -154px;
  *margin-left: -3px;
  filter: alpha(opacity=0);
  -moz-opacity: .0;
  opacity: 0.0;
  cursor: pointer;
}
-->
</style>
</head>
<body>
  <input id="text" class="text" type="text" />
  <span class="file"><input id="file" type="file" /></span>

  <script type="text/javascript">
  <!--
  var file = document.getElementById("file");
  var text = document.getElementById("text");
  file.onchange = type;
  function type() {
    text.value = file.value;
  }
  -->
  </script>
</body>
</html>

這份程式碼在做什麼

.text 是一般文字輸入框,負責顯示使用者選到的檔名,樣式完全由你掌控。

.file 是一個固定尺寸的容器,背景圖 /img/ll.png 就是你畫的「瀏覽」按鈕,overflow: hidden 確保內容不會溢出。

#file 是真正的 file input。它被設成 width: 0 搭配 opacity: 0 完全透明,再用負的 margin-left 把點擊區域挪到自訂按鈕上。因為元素本身還在,使用者點擊時依然會觸發原生的檔案選擇視窗——這正是整個技巧能成立的關鍵:不要 display: none 掉真正的 input,否則它就點不動了。

那段 JavaScript 只負責一件事:把 file input 的值同步寫進文字框,讓使用者看到自己選了哪個檔案。

幾個實務提醒

filter: alpha(opacity=0) 是 IE 的私有寫法,-moz-opacity 是舊 Firefox 的,標準的 opacity 才是現在該用的。三個並列是為了相容當時的瀏覽器,今天只留 opacity 就好。

另外,讓真正的 input 保持透明但可互動,對鍵盤使用者來說仍是可聚焦的,這比 display: none 友善得多。若要更嚴謹,建議幫 <span class="file"> 加上 :focus-within 樣式,讓鍵盤 Tab 到這裡時有明確的視覺回饋。

最後,檔名同步這件事只能顯示名稱,真正的檔案內容仍要送到後端處理。前端做任何樣式變化都不改變這個事實,也不該被當成檔案驗證的手段。

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