vue 自制图片放大组件

新建组件 -- Enlarge.vue

<template>
  <transition 
    name="fade" 
    mode="out-in">
    <div 
      v-show="url" 
      class="area"
      :style="{
        left: `${x}px`,
        top: `${y}px`
      }">
      <img 
        :src="url" 
        :style="{
          left: `${left}px`, 
          top: `${top}px`,
          width,
          height
        }" >
    </div>
  </transition>
</template>

<script>
export default {
  data () {
    return {
      target: null,
      url: null,
      width: 'auto',
      height: 'auto',
      left: 0,
      top: 0,
      x: 0,
      y: 0
    }
  },
  props: {
    scale: {
      type: Number,
      default: 2
    }
  },
  methods: {
    enter(e = {}){
      let { target } = e;
      if(!target) return;
      this.target = target;
      this.target.addEventListener('mousemove', this.move);
      this.target.addEventListener('mouseleave', this.leave);
      this.url = target.getAttribute('src');
      this.width = `${target.offsetWidth * this.scale}px`;
      this.height = `${target.offsetHeight * this.scale}px`;
      //预览放大图片的位置
      let rect = target.getBoundingClientRect();
      this.x = rect.left + target.offsetWidth + 20;
      this.y = rect.top;
    },
    move(e){
      let { offsetX, offsetY } = e;
      this.left = -(offsetX * this.scale - (this.target.offsetWidth / 2));
      this.top = -(offsetY * this.scale - (this.target.offsetHeight / 2));
    },
    leave(){
      this.target.removeEventListener('mousemove', this.move);
      this.url = null;
    }
  }
}
</script>

<style lang="scss" scoped>
.area{
  width: 495px;
  height: 495px;
  position: fixed;
  z-index: 100;
  overflow: hidden;
  background-color: #FFF;
  border: 1px solid #aaa;
  img{
    position: absolute;
    object-fit: contain;
  }
}
.fade-leave-active,
.fade-enter-active {
  transition: all 0.3s;
  opacity: 1;
}
.fade-enter {
  opacity: 0;
}
.fade-leave-to {
  opacity: 0;
}
</style>

在需要使用的地方引入,并且调用

<template>
  <div>
    <img
      src="/static/img/xxx.jpg"
      @mouseenter="$refs.enlargeRef.enter($event)" />
    <Enlarge
      ref="enlargeRef" />
  </div>
</template>

<script>
import Enlarge from '@/components/Enlarge.vue'
export default {
  components: {
    Enlarge
  }
}
</script>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容