本地input选择图片实时显示,可批量

前端 2018-04-26

代码描述:选择图片可以实时显示

选择图片后,获取当前input变化之后的图片地址,用这个方法能获取到当前选择的文件的各种信息

CSS

<style>
#imgPreview { float: left; border: none; } 
#imgPreview img { margin-right: 10px; width: 50px; height: 50px; } 
upload-img { display: block; float: left; width: 50px; height: 50px; overflow: hidden; position: relative; background: url("../images/self/upload.png") no-repeat 0; background-size: contain; } 
.upload-img input { height: 50px; opacity: 1; filter: alpha(opacity=0); position: absolute; top: 0; right: 0; }
</style>

HTML

<div class="box"></div>
<input class="a" type="file">

JS

<script type="text/javascript">
$('.a').change(function(e) {
    var _URL = window.URL || window.webkitURL;
    var file, img;
    if ((file = this.files[0])) {
        img = new Image();

        if($(".box li").length <= 2){

            img.onload = function() {
                $('.box').append("<li><img src=" + this.src +"></li>");
                // $('.img').attr('src', this.src);
                console.log(this.width)
            };

        } else{
            
            alert("2")

        }
        
        img.src = _URL.createObjectURL(file);
    }
})
</script>