首页 > 技术文章 > html中进行文件的选择(input.click())

zp900704 2016-01-24 17:59 原文

html中的<input type="file"/>标签没法进行定制,因此,比较通用的一种实现方式是将”input file“设置为透明,再在底部添加一个背景节点进行显示

1     <div style="position:relative">
2         <a style="width:100px;height:30px;">请选择文件</a><!--其他标签也可以-->
3         <input type="file" style="position:absolute;top:0px;left:0px;width:100px;height:30px;opacity:0"/>
4     </div>

还有一种比较通用的方式是有别的标签的click时间进行触发实现如下:

 1 !DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3     <head>
 4         <title></title>
 5         <script src="../jquery.js"></script>
 6         <script>
 7             function SelectFile() {
 8                 var promise = $.Deferred();
 9                 var input = $("<input type='file'/>");
10                 if (ischrome) {
11                     //chrome是使用的非阻塞 选择文件是不会中断主线程的js执行的
12                     
13                     input.change(function () {
14                         promise.resolve(this.files);
15                     });
16                     input.click();
17                 } else {
18                     //ie firefo是阻塞的 选择文件会中断主线程的js执行
19                     input.click();
20                     var files = input[0].files;
21                     if (files.length > 0) {
22                         promise.resolve(files);
23                     }
24                 }
25                 return promise;
26             }
27             $(document).ready(function () {
28                 $("button").click(function () {
29                     var selectfile = SelectFile();
30                     selectfile.done(function (files) {
31                         console.log("用户选择的文件为:");
32                         console.log(files);
33                     })
34                 })
35             })
36         </script>
37     </head>
38     <body>
39         <button>请选择文件</button>
40     </body>
41 </html>

 

推荐阅读