用加号图标代替input type=file实现添加文件,清空input file

在这里插入图片描述在这里插入图片描述
效果图如上,通过点击该加号图片可以实现input选择文件,原理即在该图片上面写了个input隐藏,在图片点击事件中添加input的模拟点击。

<input class="mui-hidden" type="file" id="inputBox" accept="image/*" capture="camera">//input
<div id="photo" class="photo" @click="choosePhoto"></div>//加号图标
<div id="remove" class="remove" style="display: none;"></div>//删除图标

图片点击事件

choosePhoto(){
  var input = mui("#inputBox")[0];
   input.click();//模拟点击
   input.addEventListener("change",function(){ //监听input变化事件
       var reader = new FileReader();
       reader.readAsDataURL(input.files[0]);
       reader.onload = function(){
           //读取完成后,数据保存在对象的result属性中,直接赋值给src可实现预览
           var str = '';
           str = '<img id="waste_img" class="waste_img" src="'+this.result+'" />';
           mui('#photo')[0].insertAdjacentHTML('beforeBegin',str);
           mui('#photo')[0].style.display='none';
           mui('#remove')[0].style.display='';
       }
   })
}

删除点击事件(同时利用重建input实现清空file)

  	mui('#remove')[0].addEventListener('tap',function(){
   		var btnArray = ['否', '是'];
           mui.confirm('确认删除?', '温馨提示', btnArray, function(e) {
               if (e.index == 1) {
                    obj = mui('#waste_img')[0];
	        		obj.parentNode.removeChild(obj);
	        		mui('#photo')[0].style.display='';
	        		mui('#remove')[0].style.display='none';
	        		var file =mui("#inputBox")[0];
		            file.outerHTML = file.outerHTML;
               } else {
                   return;
               }
           },'div')
   	})

发布了25 篇原创文章 · 获赞 0 · 访问量 1490

猜你喜欢

转载自blog.csdn.net/u014681799/article/details/103104730