jq 图片上传前预览

html:

<div class="form_upload">
    <input type="file" id="uploadImg" name="" accept="image/*">
    <label for="uploadImg" class="upload_btn">
        <i class="icon"></i>
        <img src="" alt="">
    </label>
</div>

css:

input[type="file"]{ display: none;}
.upload_btn{flex:0 0 auto;margin:0 0.266667rem 0.266667rem 0;display: -webkit-flex;display: flex;align-items: center;justify-content: center;width:1.6rem;height: 1.6rem;background: #F2F7FC;border:1px solid #eee;border-radius: 3px;}
.upload_btn .icon{ width: 0.666667rem;height: 0.666667rem;background: url(/static/user/lottery/images/icon_upload@2x.png) no-repeat center;background-size: cover;display: block;}
.upload_btn img{display: none;}
.upload_btn.isUpload{background: #fff;}
.upload_btn.isUpload .icon{display: none;}
.upload_btn.isUpload img{display: block;}

jq:

<script src="/static/user/lottery/js/jquery-3.2.0.js"></script>
<script>
  $(function(){
    // 上传
       $(document).on('click', '.upload_btn', function(event) {
         var id=event.currentTarget.htmlFor;
      onChange(id)
    });
  })

  // 上传图片预览        
  function onChange(id){
    $("#"+id).change(function(e) {
      var imgBox = e.target;
      uploadImg($(this), imgBox)
    });
  }
  function uploadImg(element, tag) {
    var preview = element.siblings('.upload_btn');
    var file = tag.files[0];
    var imgSrc;
    if(file){
      var reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = function() {
        console.log(this.result);
        imgSrc = this.result;
        preview.addClass('isUpload');
        preview.find("img").attr("src", imgSrc);
      };                
    }
  }
</script>

 

posted @ 2019-03-28 16:44  十一是假期啊  阅读(302)  评论(0编辑  收藏  举报