DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS進階教程
用 CSS 美化 input file 上傳按鈕的實戰做法
編輯:CSS進階教程     

做表單時,input、textarea、button 這幾類元素的樣式都比較好定義,真正讓人頭疼的往往是 select 和 input file。input file 在系統默認下的外觀幾乎無法直接改動:

我們最多只能通過給 input 加 border 來稍微改變它系統默認的樣子:

如果想讓那個「瀏覽」按鈕更漂亮一些,比如設定背景色,甚至用一張背景圖片取而代之,光靠 CSS 直接定義 input file 是辦不到的。偶然間看到一篇文章,作者的思路是把系統默認的按鈕透明度設為 0,再寫一個 label 標籤的樣式蓋在透明按鈕上面,藉此實現美化。

我照著這個思路實驗了一下,代碼如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>input file的另類做法</title>
<style type="text/css">
<!--
* { font-size:12px}
body { margin:0}
.line { position:relative; float:left; padding:8px 0}
.line span { float:left}
input { border:1px solid #888; vertical-align:middle}
.file { position:absolute; left:90px; top:8px; display:none;filter:alpha(opacity=0);opacity:0}
.file1 { padding:2px 10px; display:block; float:left; background:#FF66CC; color:#fff; z-index:1; margin-left:5px; vertical-align:middle; cursor: pointer}
.inputstyle { width:150px; border:1px solid #888; z-index:99}
-->
</style>
</head>
<body>
<div class="line"> <span>
  <label>上傳文件:</label>
  <input name="" type="text" id="viewfile" onmouseout="document.getElementById('upload').style.display='none';" class="inputstyle" />
  </span>
  <label for="unload" onmouseover="document.getElementById('upload').style.display='block';" class="file1">浏覽...</label>
  <input type="file" onchange="document.getElementById('viewfile').value=this.value;this.style.display='none';" class="file" id="upload" />
</div>
</body>
</html>

效果:

這種做法雖然多寫了不少標籤,但這種「偷梁換柱」的思路還是很值得琢磨的。至於有沒有更簡潔、更科學的方案,則有待我們繼續探索。

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