注意:上传文件一般使用的是input标签,如果想要改样式,让input不显示,可以把input标签放入<leabel>标签中,然后让input标签 display:none;
案例1:上传单个图片,添加按钮不消失
html
<div class="addPicture clearfix"> <!-- 图片显示区域 --> <div class="addPictureImg"></div> <!-- 添加图片 --> <div class="addPictureDiv"> <label class="pictureDivCon"> <input type=‘file‘ id="imgInp"> <i class="iconfont icon-tianjiatupian"></i> <p>点击添加图片</p> </label> </div> </div>
css
.addPictureImg { width: 28%; float: left; position: relative; display: none; margin-right: 1rem; margin-bottom: 1rem; } .addImg1{ width: 100%; height: 80px; display: inline-block; } .addPictureDiv { float: left; width: 28%; height: 80px; text-align: center; margin-right: 1rem; background-color: #EBEBEB; vertical-align: middle; } .pictureDivCon { margin-top: 2rem; display: block; } .pictureDivCon input{ display: none; } .addPictureDiv i{ font-size: 3rem; color: #50A4FA; } .addPictureDiv p { font-size: 0.8rem; }
js
//上传图片 function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $(‘#blah‘).attr(‘src‘, e.target.result); }; reader.readAsDataURL(input.files[0]); } } $("#imgInp").change(function(){ readURL(this); }); //上传文件的图片 var addPictureImgdy = $(‘.addPictureImg‘) //点击input时动态创建Img for(var i=0; i<10; i++) { $(‘#imgInp‘).click(function() { var str = "<img src=‘#‘ alt=‘添加图片‘ class=‘addImg1‘ id=‘blah‘><i class=‘iconfont icon-guanbi addPictureClose‘></i>" $(‘.addPictureImg‘).html(str) $(‘.addPictureImg‘).css(‘display‘,‘block‘) //点击关闭图标删除图片 $(‘.addPictureClose‘).click(function() { $(this).parent().css(‘display‘,‘none‘); }); }); }
案例2:上传图片,图片覆盖添加按钮
html
<div class="purchConRight uploadImg"> //此处的添加图片按钮是个图片 <img src="../../uploads/camera.png" width="100" height="100"> <input type="file" onchange="uploads(this)"/> </div>
css
.uploadImg{ position: relative; } .uploadImg input[type=file]{ position: absolute; left: 0; height: 100px; width: 100px; opacity: 0; }
js
function uploads(fileDom) { //判断是否支持FileReader if (window.FileReader) { var reader = new FileReader(); } else { alert("您的设备不支持图片预览功能,如需该功能请升级您的设备!"); } //获取文件信息 var file = fileDom.files[0]; var imageType = /^image\//; //是否是图片 if (!imageType.test(file.type)) { alert("请选择正确的图片!"); }else { //读取完成 reader.onload = function (e) { //获取图片dom var img = $(fileDom).prev(); //图片路径设置为读取的图片 img[0].src = e.target.result; }; reader.readAsDataURL(file); } }
时间: 2024-11-09 19:14:44