vue+input file上传图片并以圆形展示代码分享(升级版增加遮罩)

24 篇文章 3 订阅
11 篇文章 0 订阅

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
      }
    },

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值