h5-上传图片预览

时间:2021-08-28 13:17:26

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

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

<script>

  h5-上传图片预览

//建立一個可存取到該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>