在實際項目中,常常須要用戶選擇圖片以便後續的上傳,這時要用到Html的input,並將其type設置爲file。原生的input上傳圖片按鈕一般沒法符合設計稿,個人作法是將其透明度設置爲0,再把寬度高度設置爲100%。css
除此以外,一般還須要前端回顯圖片,從新選擇圖片。這裏用到FileReader類。html
原生的選擇框:
理想的選擇框:
圖片回顯及從新選擇:前端
vue + elementUI,這裏使用vue單文件組件(SFC)實現,但核心代碼與所選框架與關。vue
<!-- 圖片上傳框 --> <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>
<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>
<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>
本文主要實現三個需求:框架
opacity
設置爲0;