当有些场景不适合使用其他库实现图片预览时,可使用以下代码,代码基于vue2版本,已验证,可以正常运行,注意缺失的图片,自己在路径下补一张就可以
部分代码来自于国内直连GPT4/Claude
代码如下
<template>
<div class="container2132">
<div class="overlay" v-if="isZoomed" @click="toggleZoom"></div>
<img
:src="imageSrc"
@click="toggleZoom"
:class="{'zoomed': isZoomed}"
class="zoomable-image"
ref="image"
/>
</div>
</template>
<script>
export default {
data() {
return {
isZoomed: false,
originalWidth: 0,
originalHeight: 0,
imageSrc: require('./images/testimg.jpg') // 替换为你的图片路径
};
},
methods: {
toggleZoom() {
if (!this.isZoomed) {
const img = this.$refs.image;
this.originalWidth = img.naturalWidth;
this.originalHeight = img.naturalHeight;
img.style.width = `${
this.originalWidth}px`;
img.style.height = `${
this.originalHeight}px`;
} else {
const img = this.$refs.image;
img.style.width = '';
img.style.height = '';
}
this.isZoomed = !this.isZoomed;
}
}
};
</script>
<style scoped>
.container2132 {
width: 100vw;
height: 100vh;
}
.container2132 img{
width: 120px;
}
.zoomable-image {
transition: transform 0.3s ease-in-out, width 0.3s ease-in-out, height 0.3s ease-in-out;
cursor: pointer;
position: relative; /* 添加 position: relative */
z-index: 1; /* 设置初始的 z-index */
max-width: 100%; /* 确保图片不会超出容器 */
height: auto; /* 保持图片的纵横比 */
}
.zoomable-image.zoomed {
transform: none; /* 移除放大效果 */
z-index: 1001; /* 放大时提高 z-index */
}
.overlay {
position: fixed; /* 确保遮罩层覆盖整个页面 */
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.7); /* 遮罩层颜色和透明度 */
z-index: 1000; /* 确保遮罩层在图片之下 */
}
.loading-mask {
position: absolute;
width: 100%;
height: calc(100% - 64px);
margin-top: 64px;
background: rgba(255, 255, 255, 0.5);
z-index: 99999;
display: flex;
justify-content: center;
align-items: center;
}
.loading-mask img{
width: 60px;
height: 60px;
}
</style>