html 部分:
<div class="upload-pics-item small">
<span class="iconfont upload-icon icon-xiangji f-20"></span>
<input type="file" name="pic1" value="" class="upload-pic-input">
<p class="f-12">添加图片</p>
<img src="" alt="">
</div>
js 部分:
let dom = document.getElementsByClassName('upload-pic-input');
Array.from(dom).forEach(item=>{
item.onchange = function(){
$(this).parent().find('p').hide();
$(this).parent().find('.iconfont').hide();
let src = getObjectURL(this.files[0]);
if(src){
$(this).parent().find('img').attr('src',src);
}else{
$(this).parent().find('img').attr('alt',this.files[0]);
}
}
})
// 判断浏览器是否支持 createObjectURL api
function getObjectURL(file) {
var url = null;
if (window.createObjectURL!=undefined) {
url = window.createObjectURL(file) ;
} else if (window.URL!=undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file) ;
} else if (window.webkitURL!=undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file) ;
}
return url ;
}