JS 头像显示

HTML

<div class="form-group">
    <label class="col-sm-3 control-label">头像</label>
    <div class="col-sm-9">
        <label for="avatar-id"><img src="{% static 'img/default.png' %}" alt="" id="avatar-img"></label>
        <input type="file" id="avatar-id" class="hidden">

    </div>
</div>

JS

    // 1.input file 上传标签绑定change事件
    $("#avatar-id").change(function () {
        // 2.创建一个读取文件的对象
        var fileReader = new FileReader()
        // 3.读取选择的对象
        fileReader.readAsDataURL($(this)[0].files[0])
        // 注意:文件的读取需要事件
        fileReader.onload = function () {
            // 4.读取完文件后,修改img标签的src属性
            $("#avatar-img").attr("src", fileReader.result)
        }
    });

 

posted @ 2019-08-08 07:36  市丸银  阅读(494)  评论(0编辑  收藏  举报