1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > html输入框自定义图片 图片input框自定义样式及前端回显

html输入框自定义图片 图片input框自定义样式及前端回显

时间:2021-03-24 04:18:34

相关推荐

html输入框自定义图片 图片input框自定义样式及前端回显

前言

在实际项目中,经常需要用户选择图片以便后续的上传,这时要用到Html的input,并将其type设置为file。原生的input上传图片按钮通常无法符合设计稿,我的做法是将其透明度设置为0,再把宽度高度设置为100%。

除此之外,通常还需要前端回显图片,重新选择图片。这里用到FileReader类。

原生的选择框:

理想的选择框:

图片回显及重新选择:

基础框架

vue + elementUI,这里使用vue单文件组件(SFC)实现,但核心代码与所选框架与关。

代码实现

html部分

添加照片

JS部分

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 = ''

}

}

}

CSS部分

.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%;

}

}

总结

本文主要实现三个需求:

input框样式自定义,主要是通过将透明度opacity设置为0;

用户选择图片后回显在前端页面上,主要是运用FileReader()技术;

增加删除按钮,用户可重新选择,主要是将input框的files对象的value属性置空。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。