以下是用 vue
技术栈 实现的
总有要实现点击查看图片效果功能的时候
这时候 可以直接用我的代码,创建个vue文件
把代码放入即可,我是以封装成组件的方法来使用的
方便小白使用 引用方法:
// 文件引用,文件位置自行改变
import dialogImg from '@/views/components/dialogImg';
// 注册 挂载组件
components:{dialogImg},
方便小白使用 使用方法:
里面的 dialogimgShow
imgList
imgIndex
数据,自行在data中声明
<dialogImg :dialogimgShow="dialogimgShow" @changeShow="(e)=>dialogimgShow = e" :imgList="imgList" :imgIndex="imgIndex"></dialogImg>
话不多说,直接上代码
<template>
<div class="content" v-if="show" @click="handleOuterClick">
<div class="magnify">
<img :src="imgList[imgIndex]" alt="">
<div class="left caozuo"> {{'<'}} </div>
<div class="right caozuo"> {{'>'}} </div>
<div class="off" @click="off">{{'x'}}</div>
</div>
</div>
</template>
<script>
export default {
name:'dialogImg',
data(){
return{
show:false
}
},
props:{
dialogimgShow:{
type:Boolean,
default:false
},
imgList:{
type:Array,
default:()=>[]
},
imgIndex:{
type:Number,
default:0
}
},
watch:{
dialogimgShow (newValue,oldValue){
// this.$emit('update:dialogimgShow', newValue)
this.show = newValue
}
},
methods:{
left(){ // 向左切换
const length = this.imgList.length - 1
if(this.imgIndex === 0) return this.imgIndex = length
this.imgIndex -= 1
},
right(){ // 向右切换
const length = this.imgList.length - 1
if(this.imgIndex === length){
this.imgIndex = 0
}else{
this.imgIndex += 1
}
},
off(){ // 关闭事件
this.show = false
this.$emit('changeShow',this.show)
},
handleOuterClick(event) {
const pan = event.target.matches('img') || event.target.matches('.caozuo')
// 判断点击的位置是否不是目标DOM元素
if (!pan) {
this.off()
}
},
}
}
</script>
<style scoped lang="scss">
.content{
min-width: 100vw;
min-height: 100vh;
position: fixed;
top: 0;
left: 0;
z-index: 3000;
}
.magnify{
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
width: 900px;
height: 700px;
background-color: rgba($color: #000000, $alpha: 0.6);
img{
width: 100%;
height: 100%;
object-fit: contain;/* 图片完整展示在容器内,可能有空白 */
}
.caozuo{
height: 700px;
width: 50px;
display: flex;
justify-content: center;
align-items: center;
background: #ccc;
font-size: 40px;
font-weight: 600;
opacity: 0.6;
cursor: pointer;
}
.left{
position: absolute;
top: 50%;
left: -60px;
transform: translateY(-50%);
}
.right{
position: absolute;
top: 50%;
right: -60px;
transform: translateY(-50%);
}
.off{
position: absolute;
top: 5%;
right: 5%;
font-size: 38px;
font-weight: 600;
cursor: pointer;
padding: 20px;
color: #f20e0e;
}
}
</style>