从Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1)开始,你能够隐藏掉默认的的
文件输入框<input>
元素,使用自定义的界面来充当打开文件选择对话框的按钮。实现起来很简单,你只须要使用样式display:none把本来的
文件输入框隐藏掉,而后在须要的时候调用它的click()
方法就好了。css
考虑下面的HTML:html
<input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)"><a href="#" id="fileSelect">Select some files</a>
处理 click
事件的代码以下:web
var fileSelect = document.getElementById("fileSelect"), fileElem = document.getElementById("fileElem");fileSelect.addEventListener("click", function (e) { if (fileElem) { fileElem.click(); } e.preventDefault(); // prevent navigation to "#"}, false);
这样,你就能任意改变这个文件选择按钮的样式了。chrome
参考:https://developer.mozilla.org/zh-CN/docs/Using_files_from_web_applications#%E5%9C%A8%E9%9A%90%E8%97%8F%E7%9A%84%E6%96%87%E4%BB%B6%E8%BE%93%E5%85%A5%E6%A1%86%E4%B8%8A%E8%B0%83%E7%94%A8click%28%29%E6%96%B9%E6%B3%95segmentfault
https://segmentfault.com/q/1010000004430586
安全
方法二:
app
相信不少人都碰到过这个问题,文件上传控件透明后有的要点击两次才能弹出选择文件窗口,这里将将介绍如何避免要双击,只须要单击是能够实现的。 原本一直无意留意这个图片上传file按钮的BUG,由于有时候为了效果好看有时候咱们要作点什么好比隐藏input模拟点击。FF能够chrome也可 以,惟独IE不行,报安全错误。因此仍是得找方法解决,最终在某网站找到了,只是把input按钮的透明度改成0而后定位到最顶层,虽然透明,不表示没 有,这样点击上传时不影响效果又能实现所要的效果。真心不错。方法其实很简单。下面就介绍如何操做。网站
示例效果解图以下:ui
一、特别注意样式的写法。跟文件上传控件的参数this
值得注意的是height:130%,font-size:100px,这样显示上传的文字就会变大,把点击的区域变大了,这样就能够单击能够了。样式以下:
.upload{width:100px;height:100px;line-height:100px;position:relative;border:1px solid #ddd;background:#f6f6f6;text-align:center;color:#333;overflow:hidden;} #fileupload{position:absolute;bottom:0;left:0;font-size:100px;height:130%;width:100%;z-index:1;opacity:0;filter:alpha(opacity=0);}
二、完整代码以下:
<!DOCTYPE> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>file点击上传控件</title> <style> .upload{width:100px;height:100px;line-height:100px;position:relative;border:1px solid #ddd;background:#f6f6f6;text-align:center;color:#333;overflow:hidden;} #fileupload{position:absolute;bottom:0;left:0;font-size:100px;height:130%;width:100%;z-index:1;opacity:0;filter:alpha(opacity=0);} </style> </head> <body> <div class="upload"> 点击上传 <input type="file" id="fileupload" size="100" /> </div> </body> </html>