圖片input框自定義樣式及前端回顯

前言

在實際項目中,常常須要用戶選擇圖片以便後續的上傳,這時要用到Html的input,並將其type設置爲file。原生的input上傳圖片按鈕一般沒法符合設計稿,個人作法是將其透明度設置爲0,再把寬度高度設置爲100%。css

除此以外,一般還須要前端回顯圖片,從新選擇圖片。這裏用到FileReader類。html

原生的選擇框:
image.png
理想的選擇框:
image.png
圖片回顯及從新選擇:
test2.gif前端

基礎框架

vue + elementUI,這裏使用vue單文件組件(SFC)實現,但核心代碼與所選框架與關。vue

代碼實現

html部分
<!-- 圖片上傳框 -->
<div v-show="!imgUploaded" v-loading="loading1" class="upload_block" element-loading-text="圖片正在上傳" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
<img src="@/icons/add-file.png" alt="add" class="add_tag">
<div class="add_tip">添加照片</div>
<input id="img_input" type="file" class="file_input" multiple @change="uploadFile()">
</div>

<!-- 圖片回顯框 -->
<div v-if="imgUploaded" id="img_show">
<img :src="imgShow" alt="" class="img_show">
<!-- 圖片有上角顯示刪除角標 -->
<img src="@/icons/del_img.png" alt="del" class="del_tag" @click="delImg()">
</div>
JS部分
<script>
export default {
  data() {
    return {
      imgUploaded: false,
      loading1: false,
      imgShow: '',
    }
  },
  methods: {
    uploadFile() {
      let file = document.getElementById('img_input').files[0]
      if (!/image\/\w+/.test(file.type)) {
        this.$message.error('文件必須爲圖片!')
        return
      }
      // 利用FileReader讀取圖片實現回顯
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = (e) => {
        this.imgShow = e.target.result
      }
      if (!file) {
        return
      }
    },
    // 刪除圖片功能,以便用戶從新選擇
    delImg() {
      this.imgUploaded = false
      const files = document.getElementById('img_input')
      files.value = ''
    }
  }
}
</script>
CSS部分
<style lang="scss">
.container {
  .img_uploaded {
    padding-bottom: 40px;
    height: auto;
  }

  .img_show {
    max-width: 510px;
    height: auto;
  }

  // 刪除圖片按鈕
  .del_tag {
    position: absolute;
    right: 2px;
    top: 2px;
    width: 24px;
    height: 24px;
    cursor: pointer;
  }

  #img_show {
    position: relative;
    display: inline-block;
  }

  .upload_block {
    display: inline-block;
    text-align: center;
    width:360px;
    height:220px;
    background: #FFFFFF;
    border: 1px solid #CFD8DC;
    border-radius:4px;
  }

  .upload_block .add_tag {
    margin-top: 76px;
    width: 33px;
    height: 33px;
  }

  .upload_block .add_tip {
    margin-top: 31px;
    font-size:14px;
    color: #90A4AE;
  }

   // 原生的Input標籤
  .file_input {
    position: relative;
    right: 0;
    top: -162px;
    opacity: 0;
    filter: alpha(opacity=0);
    cursor: pointer;
    width: 100%;
    height: 100%;
  }
}
</style>

總結

本文主要實現三個需求:框架

  1. input框樣式自定義,主要是經過將透明度opacity設置爲0;
  2. 用戶選擇圖片後回顯在前端頁面上,主要是運用FileReader()技術;
  3. 增長刪除按鈕,用戶可從新選擇,主要是將input框的files對象的value屬性置空。
相關文章
相關標籤/搜索