input type=file 附带按钮的样式几乎不被CSS所控制。在其它按钮应用了特殊格式之后,这种按钮在界面上显的极不协调。
就目前流行的几大浏览器来看,试图用样式表控制这种按钮的样式(或更改按钮上文字)都是不可能的。因而一些人采取隐藏input type=file而采用标准的按钮来代替它的方法。以下是一种比较简洁的实现,可以工作在IE中。其中的关键是,IE为Form控件提供了 click()方法,以便用程序指令替代人工点击。
<input type=file name=browse style="display: none;">
<input type=text name=file>
<input type=button style="color:white;background-color: #0066CC;height:20px; border: solid 1px #000; width: 80px;text-align:center;" onClick="browse.disabled=false;browse.click();file.value=browse.value;browse.disabled=true" value="Select a File">
但是这种方法不适合在firefox中使用
下面是另一种办法
- Take a normal
<input type="file">
and put it in an element with position: relative
. - To this same parent element, add a normal
<input>
and an image, which have the correct styles. Position these elements absolutely, so that they occupy the same place as the <input type="file">
. - Set the
z-index
of the <input type="file">
to 2
so that it lies on top of the styled input/image. - Finally, set the
opacity
of the <input type="file">
to 0
. The <input type="file">
now becomes effectively invisible, and the styles input/image shines through, but you can still click on the "Browse" button. If the button is positioned on top of the image, the user appears to click on the image and gets the normal file selection window.
(Note that you can't use visibility: hidden
, because a truly invisible element is unclickable, too, and we need the <input type="file">
to remain clickable
Until here the effect can be achieved through pure CSS. However, one feature is still lacking.
- When the user has selected a file, the visible, fake input field should show the correct path to this file, as a normal
<input type="file">
would. It's simply a matter of copying the new value of the <input type="file">
to the fake input field, but we need JavaScript to do this.
The HTML/CSS structure
I've decided on the following HTML/CSS approach:
div.fileinputs {
position: relative;
}
div.fakefile {
position: absolute;
top: 0px;
left: 0px;
z-index: 1;
}
input.file {
position: relative;
text-align: right;
-moz-opacity:0 ;
filter:alpha(opacity: 0);
opacity: 0;
z-index: 2;
}
<div class="fileinputs">
<input type="file" class="file" />
<div class="fakefile">
<input />
<img src="search.gif" />
</div>
</div>
原文:http://www.quirksmode.org/dom/inputfile.html