基于vue2手写图片放大预览功能,带有动画效果【已验证,功能正常】

当有些场景不适合使用其他库实现图片预览时,可使用以下代码,代码基于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>

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吉吉安

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值