input file的ui定制
由于表单的file类型的外观无法通过css改变样式,加上在不同浏览器ui表现又有所不同,使得很多项目中非常需要可以自定义文件上传UI的方法。在这里,我提供两种在项目中常用的解决办法。
1.模拟点击实现UI定制
这种方法相对简单,原理是直接隐藏原有的file表单,直接在定制好UI的按钮上绑定单击事件,而单击事件中通过模拟点击file表单来触发文件选择。缺点:做法虽然比较简单,但是这种方法也有其局限性,假如你的项目的脚步是按需加载,或者存在跨
域等问题限制,模拟点击就会遇到更多的麻烦。
代码模拟
<button id="upload">upload</button> <input type="file" id="fileInput" style="display:none" /> <script type="text/javascript"> $("#upload").click(function(){ $("#fileInput").click(); }) </script>
2.通过设置透明度隐藏file表单
将file表单设置透明度为0,通过绝对定位放置在自定义UI的按钮上,这样我们看到的是自定义UI的按钮,实际点击的则是file表单。缺点:我还是比较赞同此种实现方法,很少有模拟点击出现的一些奇奇怪怪的问题,唯一遗憾的是,鼠标移动上去的指针无法变更。
代码模拟
<style type="text/css"> #fileWrap{ width: 80px; height: 20px; overflow: hidden; position: relative;} #fileWrap .fileHide{ position: absolute; left: 0;top:0; width: 80px; height: 20px; z-index: 2; opacity: 0;cursor: pointer;} #fileWrap .fileShow{ position: absolute; left: 0;top:0; width: 80px; height: 20px; z-index: 1;} </style> <div id="fileWrap"> <div class="fileHide"><input type="file" /></div> <div class="fileShow">文件上传</div> </div>