创建个vue2项目,直接把代码放到一个vue2页面内运行就好,下面代码拿来即用
<template>
<div>
<div class="replace_menu_mask" @click="closeMenu">
<img :src="replaceImg" alt="" style="width: 100%;">
</div>
<div :class="{ 'replace_menu': flag }" v-if="flag">
<div class="replace_menu_item" @click="randomBgImg">系统随机</div>
<div class="replace_menu_item">
相册<input type="file" @change="perPhotoAlbum" name="file" id="file" />
</div>
<div class="replace_menu_item item_cancel" @click="closeMenu">取消</div>
</div>
</div>
</template>
<script>
export default {
name: 'replaceMenu',
data () {
return {
flag: true, // 控制弹窗显示
replaceImg: '', // 选取的图片地址
}
},
methods: {
closeMenu () {
// 关闭弹窗
this.flag = false
},
// 本地图片读取(移动端则选择手机相册,pc端选择文件夹)
perPhotoAlbum (e) {
const that = this
let file = e.target.files[0]
that.getBase64(file).then(res => {
that.replaceImg = res // 图片地址源
// 选择完毕后关闭弹窗
this.flag = false
})
},
// 二进制流转换为base64 格式。
getBase64 (data) {
return new Promise((resolve, reject) => {
const blob = new Blob([data], {
type: "image/jpg"
}) //类型一定要写!!!
const reader = new FileReader()
reader.readAsDataURL(blob)
reader.onload = () => resolve(reader.result)
reader.onerror = (error) => reject(error)
})
},
// 随机显示图片
randomBgImg () {
// 随机图片这个自己写个随机数就好,然后抽取不同图片把路径放上去即可,这里讲的主要是从本地拿图片并转化base64格式用于显示
}
}
}
</script>
<style lang="less">
.replace_menu_mask {
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
background-color: rgba(0, 0, 0, .5);
z-index: 99;
}
.replace_menu {
width: 100%;
position: fixed;
bottom: 0;
left: 0;
z-index: 9999;
transform: translateY(1000px);
background-color: #f2f2f2;
border-top-left-radius: 0.41rem;
border-top-right-radius: 0.41rem;
animation: mobileBox 0.5s forwards ease-in-out;
.replace_menu_item:first-child {
border-top-left-radius: 0.41rem;
border-top-right-radius: 0.41rem;
}
.replace_menu_item {
text-align: center;
padding: 0.307rem;
border-bottom: 0.0205rem solid rgba(0, 0, 0, .1);
line-height: 0.41rem;
background-color: #fff;
color: #333;
position: relative;
#file {
height: 0.205rem;
}
input[type="file"] {
position: absolute;
top: 0.41rem;
right: 0;
background-color: #fff;
transform: translate(-300px, 0px) scale(4);
opacity: 0;
filter: alpha(opacity=0);
}
}
.item_cancel {
margin-top: 0.205rem;
padding: 0.41rem;
}
}
@keyframes mobileBox {
0% {
transform: translateY(1000px);
}
100% {
transform: translateY(0px);
}
}
</style>
效果图
选择完图片后直接展示了