本地图片预览并居中截取

 1 <!DOCTYPE html>
 2 <html>
 3 
 4 <head>
 5     <title>HTML5上传图片预览</title>
 6     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7     <script src="jquery-3.2.0.js"></script>
 8     <style>
 9             *{
10                 margin:0;
11                 padding: 0;
12             }
13             .con{
14                 width: 600px;
15                 height: 300px;
16                 border:1px solid #333;
17                 margin:0 auto;
18                 box-sizing: border-box;
19                 padding: 5px;
20                 border-radius: 5px;
21                 display: flex;
22             }
23             li{
24                 list-style: none;
25                 height: 150px;
26                 width: 150px;
27                 background-position:center;
28                 background-size: cover;
29                 border-radius: 5px;
30             }
31             
32     </style>
33 </head>
34 
35 <body>
36     <h3>请选择图片文件:JPG/GIF</h3>
37     <form name="form0" id="form0">
38         <input type="file" name="file0" id="file0" multiple="multiple" />
39         <br>
40         <ul class="con"></ul>
41     </form>
42     <script>
43     console.log(window)
44     $("#file0").change(function() {
45         var len = this.files.length;
46         for(var i = 0; i < len; i++){
47                 var newSrc = window.URL.createObjectURL(this.files[i]);
48                 $("<li></li>").css('backgroundImage',"url("+newSrc+")").appendTo('.con');
49         }
50     });
51     
52     </script>
53 </body>
54 
55 </html>

直接看代码吧,直接运行就好,完美的效果,但是其中的获取本地地址的方法好像还是存在一个缺陷,兼容没做。

还有一个问题是,一般的不会使用丑陋的file来实现文件的上传,一般都是在bootstrap中来使用的,直接变成了一个按钮,不错。

晚上有时间整理一个bootstrap实现预览的代码

posted @ 2017-03-22 17:11  wrestle-mania  阅读(325)  评论(0编辑  收藏  举报