一般来说,上传控件不是用flash做就是用input[type=file]元素了,但flash在IPAD上没救了,而input[type=file]在各种浏览器中又长得不是一个样子,因此已经我们需要用CSS来处理一下。听说webkit可以用-webkit-appearance:none;清除默认样式,就可以让你为所欲为了。但天朝的炮灰们(有些公司喜欢称我们为前端攻城师,那岂不就是炮灰吧,每改一次设计就烂头焦额,半死不活),是用不起这么高级的东东,我们还要兼容IE6呢。最后问群里的大大,找到解决方案。
原理大致如下,既然原来的input[type=file]元素很难看就让它消失吧。这里的消失是让它其透明化,并在外面为其包一层,那个父元素相对定位。然后在里面添加一个DIV元素铺底,它与input[type=file]元素是兄弟,但它是绝对定位向左对齐,层级为1,input[type=file]元素是绝对定位向右对齐,层级为3。那个DIV里面再加一个input[type=text]元素,用来冒充input[type=file],我们可以对它做各种美化。好了,现在是模拟原来上传控件的浏览按钮的时候了。让那个DIV也变成一个定位元素,里面放个DIV或IMG什么,这个元素我姑且称之为伪上传按钮吧。伪上传按钮绝对定位向右对齐,层级为2。当用户点击它时,其实是点中那个透明化了的input[type=file]元素。最后是交互部分,默认选中上传文件后,此文件的路径会出现在input里面的,我们搞一个onchange事件,将input[type=file]的value值赋给input[type=text]就行了。
下面是HTML部分
<div id="file_wrapper"> <div id="file_faker"> <input /> <div id="file_btn"> 浏 览 </div> <span class="ctr"></span> <span class="cbr"></span> <!-- 隐藏真正的上传 --> </div> <input type="file" id="file_uploader" /> </div>
CSS部分
#file_wrapper {
position: relative;
width:200px;
height:20px;
display:inline-block;
}
#file_faker {
position: absolute;
top: 0px;
left: 0px;
z-index: 1;
}
/* 这是用户看到的按钮*/
#file_faker input{
width:200px;
height:18px;
}
/* 这里是按钮*/
#file_btn {
position:absolute;
top:0;
right:0;
width:60px;
height:20px;
line-height:20px;
text-align :center;
background:#878787;
color:#fff;
z-index: 2;
}
#file_uploader {
position: relative;
text-align: right;
-moz-opacity:0 ;
filter:alpha(opacity: 0);
opacity: 0;
z-index: 3;
}
/* 模拟圆角 */
.ctr,.cbr{
position:absolute;
background:#fff;
width:1px;
height:1px;
display:block;
z-index:4;
}
.ctr{
top:0px;
right:0px;
}
.cbr{
bottom:0px;
right:0px;
}
JS交互部分
window.onload = function(){ var $= function (id) { return "string" == typeof id ? document.getElementById(id) : id; }; $("file_uploader").onchange = function(){ $("text_box").value = this.value; } }