h5-上传图片预览

<div class="content_sq" style="position:relative;">
  <img src="images/create_family/add.png" alt="" id="content_img">
</div>

<input type="file" class="image" accept='image/*' style="2rem;height:2rem;position:absolute;left:50rem;top:0;" id="hide_img">

<script>

  

//建立一個可存取到該file的url
function getObjectURL(file) {
var url = null ;
if (window.createObjectURL!=undefined) { // basic
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 ;
}


$('.content_sq').click(function(){
console.log(1233);
$('.image').click();
$('.image').on("change",function(){
// var objUrl = document.getElementById("hide_img").files;
var objUrl = getObjectURL(this.files[0])
console.log(objUrl);
console.log(objUrl[0]);

if (objUrl) {
$("#content_img").attr("src", objUrl);
}
});
});
});

</script>

原文地址:https://www.cnblogs.com/peipeiyu/p/10172835.html