html
<div class="upload">
<img id="img" width="100%" height="90%" :src="oneUrl" alt="头像">
<input type="file" name="file" id="file" @change="getImgURL" title=''>
</div>
升级版html(新增遮罩)
<div class="upload">
<img id="img" width="100%" height="90%" :src="oneUrl" alt="头像">
<div class="mask">点击上传头像</div>
<input type="file" name="file" id="file" @change="getImgURL" title="">
</div>
css
.upload{
width: 80px;
height: 80px;
border: #fff 1px solid;
overflow: hidden;
border-radius: 40px;
position: relative;
//这是为了居中
left: calc(50% - 25px);
#file{
width: 100%;
height: 100%;
//将按钮覆盖图片
position: absolute;
right: 0;
//透明度调为全透明
opacity:0;
}
}
升级版css
.upload{
width: 100px;
height: 100px;
border: #fff 1px solid;
overflow: hidden;
border-radius: 50px;
position: relative;
left: calc(50% - 50px);
#file{
width: 100%;
height: 100%;
position: absolute;
right: 0;
opacity:0;
}
.mask{
line-height: 100px;
text-align: center;
color: #fff;
position: absolute;
bottom: 0px;
left: 0px;
width: 100%;
height: 0px;
background-color: transparent;
}
}
.upload:hover .mask{
height: 100%;
transition: height 500ms;
border-radius: 4px;
background-color: rgba(0, 0, 0, 0.4);
}
js(无变化)
getImgURL (event) {
// 获取上传的文件对象file
let file = event.target.files[0]
// 获取文件的后缀名,用以判断文件类型是否为图片
const fileType = file.name.substring(file.name.lastIndexOf('.') + 1)
if (fileType === 'jpg' || fileType === 'png' ||fileType === 'jpeg' ||fileType === 'JPG') {
// 判断文件大小
const size = file.size / 1024 / 1024
if (size > 1) {//size的单位为M
this.$message({
type: 'warning',
message: '文件大小不能超过1M'
})
return false
}
// FileReader对象用于读取文件
const r = new FileReader()
// onload方法将会在文件读取完成后运行
r.onload = () => {
// 将base64编码赋值给页面img的src绑定的值
this.oneUrl = r.result
}
// 读取blob或file文件对象,其中r.result是读取文件的base64编码
r.readAsDataURL(file)
} else {
this.$message({
type: 'warning',
message: '文件格式不符,请重新选择'
})
return false
}
},