vue 图片自适应屏幕大小

 父组件打开图片可以引入下面组件

<template>
  <div class="image-viewer" style="position: absolute; z-index: 9999999">
    <div class="image-container">
      <img
        :src="imageUrl"
        style=""
        alt="Image"
        @click="closeViewer"
        :style="imageStyle"  //主要代码
      />
    </div>
  </div>
</template>

<script>
export default {
  props: {
    imageUrl: String
  },
  data() {
    return {
      containerWidth: 0, //主要代码
      containerHeight: 0 //主要代码
    };
  },
  computed: {
  //主要代码
    imageStyle() {
      return {
        maxWidth: `${this.containerWidth}px`,
        maxHeight: `${this.containerHeight}px`,
        width: "auto",
        height: "auto"
      };
    }
  },
  mounted() { 
   //主要代码
    this.updateContainerSize();
    window.addEventListener("resize", this.updateContainerSize);
  },
  beforeDestroy() {
  //主要代码
    window.removeEventListener("resize", this.updateContainerSize);
  },
  methods: {
//主要代码
    updateContainerSize() {
      this.containerWidth = window.innerWidth * 0.8; // Adjust as needed
      this.containerHeight = window.innerHeight * 0.8; // Adjust as needed
    },
    closeViewer() {
      this.$emit("close");
    }
  }
};
</script>

<style scoped>
/*主要代码*/
.image-viewer {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
  overflow-y: auto;
  background: rgba(0, 0, 0, 0.4);
}
或者
.image-viewer {
 display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}
 
.image-container {
  position: relative;
  z-index: 9999;
  overflow-y: auto;
  display: inline-block;
}


 /*主要代码*/
img {
  position: static;
  object-fit: cover;
  display: block;
  max-width: 100%;
  max-height: 100%; 
  z-index: 9999999;
}
</style>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值