【JQuery】注册中实现图片预览

【Jquery】注册中实现图片预览

<div class="form-group">
  <label class="col-sm-2 control-label" style="padding: 7px 10px 0;text-align: left">头像</label>
  <div class="col-sm-10">
    <label for="id_head_photo"><img src="/static/image/default.png" alt="" id="head_photo_img" style=" 50px;height: 50px"></label>
    <input type="file" name="head_photo" id="id_head_photo" style="display: none">
    <span id="helpBlock2" class="help-block"></span>
  </div>
</div>
<script>
        // 找到头像的标签绑定change事件
        $("#id_head_photo").change(function () {
            //1.创建一个读取文件的对象
            var fileReader = new FileReader();
            //取到当前选中的头像文件
            //console.log(this.files[0]);
            //读取你选中的那个文件
            fileReader.readAsDataURL(this.files[0]);  //读取文件是需要时间的
            fileReader.onload = function () {
                //2.等上一步读完文件之后,才把图片加载到img标签中
                // attr意思是给一个标签设置属性,例如$("#head_photo_img").attr('id','default')
                $("#head_photo_img").attr("src",fileReader.result);
            };
        })
    </script>
原文地址:https://www.cnblogs.com/neymargoal/p/9677321.html