版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_39967349/article/details/78374866
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<style media="screen">
.pic{
width:100px;
height:100px;
border-radius:50% ;
margin:20px auto;
cursor: pointer;
background-image: url(./nike3.jpeg);
background-size: cover;
}
</style>
</head>
<body>
<div>
<img class="pic" src="" >
<input class="upload" name="file" accept="image/*" type="file" style="display: none"/>
</div>
<div>
<img class="pic" src="" >
<input class="upload" name="file" accept="image/*" type="file" style="display: none"/>
</div>
</body>
</html>
<script>
$(function() {
$(".pic").click(function () {
$(this).parent().find(".upload").click(); //隐藏了input:file样式后,点击头像就可以本地上传
$(this).parent().find(".upload").on("change",function(){
var objUrl = getObjectURL(this.files[0]) ; //获取图片的路径,该路径不是图片在本地的路径
if (objUrl) {
$(this).parent().find(".pic").attr("src", objUrl) ; //将图片路径存入src中,显示出图片
}
});
});
});
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 ;
}
</script>