原始的file控件是這樣的: css
<input type='file'/> html
別覺得這個是由一個text和一個button組合成的,它是一個控件,html代碼爲: post
<input type="file" name="file" />既然這樣咱們就用一個text和一個button來顯示這個file的樣式,html代碼是這樣:
<div class="file-box"> <form action="" method="post" enctype="multipart/form-data"> <input type='text' name='textfield' id='textfield' class='txt' /> <input type='button' class='btn' value='瀏覽...' /> <input type="file" name="fileField" class="file" id="fileField" size="28" onchange="document.getElementById('textfield').value=this.value" /> <input type="submit" name="submit" class="btn" value="上傳" /> </form> </div>外面的一層div是爲了給裏面的input提供位置參考,由於寫樣式的時候須要相對定位,使真正的file控件覆蓋在模擬的上面,而後隱藏掉file控件(即便file控件不可見),因此css代碼是這樣的:
.file-box{ position:relative;width:340px} .txt{ height:22px; border:1px solid #cdcdcd; width:180px;} .btn{ background-color:#FFF; border:1px solid #CDCDCD;height:24px; width:70px;} .file{ position:absolute; top:0; right:80px; height:24px; filter:alpha(opacity:0);opacity: 0;width:260px }
Demo ui
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>定義input type="file" 的樣式</title> <style type="text/css"> body{ font-size:14px;} input{ vertical-align:middle; margin:0; padding:0} .file-box{ position:relative;width:340px} .txt{ height:22px; border:1px solid #cdcdcd; width:180px;} .btn{ background-color:#FFF; border:1px solid #CDCDCD;height:24px; width:70px;} .file{ position:absolute; top:0; right:80px; height:24px; filter:alpha(opacity:0);opacity: 0;width:260px } </style> </head> <body> <div class="file-box"> <form action="" method="post" enctype="multipart/form-data"> <input type='text' name='textfield' id='textfield' class='txt' /> <input type='button' class='btn' value='瀏覽...' /> <input type="file" name="fileField" class="file" id="fileField" size="28" onchange="document.getElementById('textfield').value=this.value" /> <input type="submit" name="submit" class="btn" value="上傳" /> </form> </div> </body> </html>