移动端H5上传图片

一:先说一下单张图片上传(先上代码):

html:

1 <div class="fileBtn"> 
2         <p>点击添加图片</p>
3         <input id="fileBtn" type="file" οnchange="upload();" accept="image/*" capture="camera" multiple="multiple"/> 
4         <!--单张图片容器-->
5         <img src="" id="img"/>
6     </div>
7     <!--多张图片容器-->
8    <div class="img-box"> 
9    </div> 

css样式(由于默认file样式实在不好看,自定义透明覆盖改变了样式ps含多张图片容器div):

1 <style type="text/css">
2         #fileBtn{width: 100px;height: 100px; position: absolute;display: block;top: 0;left: 0;opacity: 0;} 
3         .fileBtn{width: 100px;height: 100px;border: 2px dashed lightskyblue;text-align: center;position: relative;left: 50px;top: 50px;}
4         .fileBtn p{line-height: 60px;}
5         #img{width: 100px;height: 100px;position: absolute;top: 0;left: 0;z-index: 10;display: none;}
6         .img{width: 100px;height: 100px;}
7         .img-box{margin-top: 80px;}
8     </style>

js代码:

1 //单张图片上传
 2     function upload(){ 
 3     var $c = document.querySelector("#fileBtn");//上传出发按钮
 4     var $d = document.querySelector("#img");//图片容器
 5     var file = $c.files[0];//获取file对象单张
 6     var reader = new FileReader();//创建filereader对象
 7         reader.readAsDataURL(file);//转换数据
 8         reader.onload = function(e){//加载ok时触发的事件
 9             console.log(file);
10         $d.setAttribute("src", e.target.result);//给图片地址,显示缩略图
11         $d.style.display="block";//样式显示
12     };
13 };  

二:多张图片上传(android不支持):

只需将在方法里改变将file全部获取并遍历;(这里还可限制上传数量就没写了;)

 1  //多张图片
 2      function uploadm(){ 
 3     var $c = document.querySelector("#fileBtn");//上传出发按钮
 4     var $d = document.querySelector(".img-box");//图片容器
 5     var file = $c.files; //获取file对象,并进行遍历
 6     console.log(file.length);
 7     for(var i=0;i<file.length;i++){
 8         var reader = new FileReader();
 9         reader.readAsDataURL(file[i]); 
10         reader.onload = function(e){ 
11         var oImg=new Image();
12         oImg.setAttribute("src", e.target.result);
13         oImg.setAttribute("class",‘img‘);
14         $d.appendChild(oImg);
15         };
16     } 
17 };  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值