自定义文件上传框

Files & media
date
Jun 4, 2014
slug
custom-inputfile
status
Published
tags
develop
summary
其实这根本就不值得写出来,只是可能前几步大家都做了,只是最后一步就忽略了。
type
Post
URL
其实这根本就不值得写出来,只是可能前几步大家都做了,只是最后一步就忽略了。
 
notion image
我们在自定义input:file的时候,一般来说都是外边包一层,里边在写一个<input type="file">, 然后将其透明值设置成0,然后再定义外层的样式来达到自定义的目的。
HTML:
<div class="upfileOutWrap">
  <div class="upfileWrap"><input type="file"></div>
  <div class="upfileBG">upload image</div>
</div>
CSS:
.upfileOutWrap {
  cursor: pointer;
  width: 199px;  height: 42px;
  line-height: 42px;
  position: relative;
}
.upfileWrap{
  width: 100%;  height: 100%;
  position: absolute;
  top:-1; left: -1;
  z-index:2;
}
.upfileWrap input{
  opacity: 0; filter: alpha(opacity=0);
  cursor: pointer;
  width: 100%; height: 100%;
  font-size: 32px;
}
.upfileBG{
  width:100%; height:100%;
  background: url(./images/upload.png) no-repeat;
  font-size: 14px;
  color: white;
  position: absolute;
  top:-1; left: -1;
  padding-left:10px;
  z-index:1;
}
notion image
可是这个时候还是有点问题,就是万恶的IE下边。
IE下边的input标签默认都是有光标的,:file也不例外,而且IE下边必须要点击”Browse”或者双击input输入框才会有效果。那么这个时候在IE下就会出现如图的莫名其妙的问题,注意左边的光标,并且还需要双击才会弹出文件选择窗口。
notion image
这个时候如果你把input透明度设置成100显示出来,就会发现原来是这样的。
notion image
所以这个时候,如果是其他标准浏览器,那么设置好input的高宽就搞定了,而IE下边,还必须考虑如何让”Browse”按钮能铺满我们所自定的div样式。这样我们才能实现IE下不出现光标,而且单击弹出文件选择窗口。
这个时候,看似毫无办法,其实我们可以选择增加字体的大小。当字体变成32px的时候,就是这个样子的。
notion image
好了,这样我们就搞定了,将input:file 继续设置为完全透明。那个可恶的光标不见了,我们也可以实现IE下单击。当然,字体到底用多大的,要视你自己定义的视觉效果来看,自己调试吧。
Final CSS:
.upfileOutWrap {
  cursor: pointer;
  width: 199px;  height: 42px;
  line-height: 42px;
  position: relative;
}
.upfileWrap{
  width: 100%;  height: 100%;
  position: absolute;
  top:-1; left: -1;
  z-index:2;
}
.upfileWrap input{
  opacity: 0; filter: alpha(opacity=0);
  cursor: pointer;
  width: 100%; height: 100%;
}
.upfileBG{
  width:100%; height:100%;
  background: url(./images/upload.png) no-repeat;
  font-size: 14px;
  color: white;
  position: absolute;
  top:-1; left: -1;
  padding-left:10px;
  z-index:1;
}
 

© Hivan Du 2021 - 2023