图片放大器组件
<template>
<div class="img-view" @click="getClose" :style="cssVar" v-show="ifImgShow">
<div class="img-layer">
<img :src="imgSrc" alt="图片地址错误" />
</div>
</div>
</template>
<script>
export default {
props: {
ifImgShow: {
type: Boolean,
default: false,
},
imgSrc: {
type: String,
default: '',
},
imgSite: {
type: Object,
default: () => {
return {}
},
},
},
data() {
return {
H: 0,
W: 0,
}
},
computed: {
cssVar({ H, W }) {
const _site = {
'--height': H,
'--width': W,
}
return _site
},
},
watch: {
ifImgShow(val) {
if (val) {
const _H = document.body.offsetHeight ?? 0 //容器高度
const _W = document.body.offsetWidth ?? 0 //容器宽度
const V = _H / this.imgSite.height > _W / this.imgSite.width //容器和图片的宽高比,是否高比大于宽比
this.H = V ? null : '90vh'
this.W = V ? '90vw' : null
}
},
},
methods: {
/**
* @description: 关闭图片放大
* @return void
*/
getClose() {
this.$emit('closeBigImg')
},
},
}
</script>
<style>
.img-view {
.img-layer {
width: 100%;
height: 100%;
position: fixed;
z-index: 5; //保证是容器内最大的z-index
top: 0;
left: 0;
background: rgba(0, 0, 0, 0.7);
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
img {
height: var(--height);
width: var(--width);
}
}
}
</style>
父组件
<!-- 需要放大的富文本 -->
<div @click="setImgBigger" v-html="" />
<!-- 图片放大组件 -->
<big-img
:ifImgShow="ifShowBigger"
:imgSrc="imgSrc"
:imgSite="imgSite"
@closeBigImg="ifShowBigger = false"
/>
data() {
return {
ifShowBigger: false, //图片放大器开关
imgSite: {
height: 0,
width: 0,
}, //图片属性
imgSrc: '', //图片地址
}
},
methods: {
/**
* @description: 图片放大
* @param e
* @return void
*/
setImgBigger(e) {
if (e.target.nodeName === 'IMG') {
this.ifShowBigger = true //打开图片放大器开关
let userAgent = navigator.userAgent //获取浏览器属性
if (userAgent.indexOf('Chrome') > -1) { //Google
this.imgSrc = e.target.currentSrc
} else { //其他
this.imgSrc = e.target.href
}
//保存原图片属性
this.imgSite.height = e.target.offsetHeight
this.imgSite.width = e.target.offsetWidth
}
},
},