如果你曾经试过,你就会知道,用纯CSS样式加HTML实现统一的上传文件按钮可能会很麻烦。看看下面的不同浏览器的截图。很明显的,他们长得很不一样。

我们的目标是创造一个简洁,用纯CSS实现的,在所有浏览器里的样子和布局是一样的上传文件按钮。我们可以这样:
步骤1.创建一个简单的HTML标记
XML/HTML Code
复制内容到剪贴板
<div class="fileUpload btn btn-primary">
<
span
>
Upload
</
span
>
<
input
type
=
"file"
class
=
"upload"
/>
</
div
>
第2步:CSS: 有点棘手了
JavaScript Code
复制内容到剪贴板
.fileUpload {
position: relative;
overflow: hidden;
margin: 10px;
}
.fileUpload input.upload { position: absolute;
top: 0;
right: 0;
margin: 0;
padding: 0;
font-size: 20px;
cursor: pointer;
opacity: 0;
filter: <span style=
"width: auto; height: auto; float: none;"
id=
"3_nwp"
><a style=
"text-decoration: none;"
mpid=
"3"
target=
"_blank"
href=
"http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=ef23810e363b7f29&k=alpha&k0=alpha&kdi0=0&luki=3&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=297f3b36e8123ef&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http://www.admin10000.com/document/5405.html&urlid=0"
id=
"3_nwl"
><span style=
"color:#0000ff;font-size:14px;width:auto;height:auto;float:none;"
>alpha</span></a></span>(opacity=0);
}
为简单起见,我使用应用了BootstrapCSS样式的按钮 (div.file-upload)。
演示:

上传按钮,显示选中的文件
不幸的是纯CSS的做不到这一点。但是,如果你真的想显示所选文件,下面的JavaScript代码片段可以帮助你。
JavaScript:
JavaScript Code
复制内容到剪贴板
document.getElementById("uploadBtn").onchange = function () {
document.getElementById(
"uploadFile"
).value =
this
.value;
};
DOM:
JavaScript Code
复制内容到剪贴板
<input id="uploadFile" placeholder="Choose File" disabled="disabled" />
<div
class
=
"fileUpload btn btn-primary"
>
<<span style=
"width: auto; height: auto; float: none;"
id=
"1_nwp"
><a style=
"text-decoration: none;"
mpid=
"1"
target=
"_blank"
href=
"http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=ef23810e363b7f29&k=span&k0=span&kdi0=0&luki=7&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=297f3b36e8123ef&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http://www.admin10000.com/document/5405.html&urlid=0"
id=
"1_nwl"
><span style=
"color:#0000ff;font-size:14px;width:auto;height:auto;float:none;"
>span</span></a></span>>Upload</span>
<input id=
"uploadBtn"
type=
"file"
class
=
"upload"
/>
</div>
演示:
