思路
点击label
元素与点击input
元素有相同的效果,因此隐藏input
即可。
代码
html
<label for="file" class="file-label">
<span class="label-placeholder">文件上传</span>
<img src="" alt="" id="img">
</label>
<input type="file" id="file" class="file-input">
javascript(用了jquery)
$("#file").on("change",function(event){
$("#img").attr("src",URL.createObjectURL(event.target.files[0]));
})
css
.file-input{
display:none;
}
.file-label{
width:5rem;
height:5rem;
border-radius: 50%;
border:solid 1px gray;
background-color: #eee;
display:flex;
align-items: center;
justify-content: center;
position: relative;
}
#img{
width:100%;
height: 100%;
border-radius: 50%;
object-fit:cover;
z-index: 1;
}
.label-placeholder{
position:absolute;
}
效果
未点击之前
点击并选中文件后