当前位置:主页 > 网页前端 > vue >

vue图片拖拉转放大缩小组件使用详解

时间:2022-05-05 10:20:44 | 栏目:vue | 点击:

vue图片拖拉转放大缩小组件的具体使用方法,供大家参考,具体内容如下

<doc>
  图片组件 - 用户放大缩小以及拖拽
</doc>
<template>
  <div style="width: 100%;position: relative;overflow: hidden;text-align: center;border: 1px solid #f1f2f3;">
    <el-button size='mini' @click="toBIgChange" icon="el-icon-zoom-in"
      style="position: absolute;top: 2px ;left: 2px;z-index: 999;"></el-button>
    <el-button size='mini' @click="toSmallChange" icon="el-icon-zoom-out"
      style="position: absolute;top: 2px ;left: 40px;z-index: 999;"></el-button>
    <img id="img" :src="src" alt="" @mousedown.prevent="dropImage" :style="{transform:'scale('+multiples+')'}">
  </div>
</template>
<script>
  export default {
    props: ['src'],
    data() {
      return {
        multiples: 1,
        odiv: null,
      }
    },
    mounted() {
      this.dropImage()
    },
    watch: {
      src(newValue, oldValue) {
        this.multiples = 1
        if (this.odiv !== null) {
          this.odiv.style.left = '0px';
          this.odiv.style.top = '0px';
        }
      },
    },
    methods: {
      toBIgChange() {
        if (this.multiples >= 2) {
          return;
        }
        this.multiples += 0.25;
      },
      // 缩小
      toSmallChange() {
        if (this.multiples <= 1) {
          return;
        }
        this.multiples -= 0.25;
      },
      // 拖拽
      dropImage(e) {
        if (e === null) {
          return
        }
        this.odiv = e.target;        //获取目标元素
        //算出鼠标相对元素的位置
        let disX = e.clientX - this.odiv.offsetLeft;
        let disY = e.clientY - this.odiv.offsetTop;
        document.onmousemove = (e) => {       //鼠标按下并移动的事件
          //用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
          let left = e.clientX - disX;
          let top = e.clientY - disY;

          //绑定元素位置到positionX和positionY上面
          this.positionX = top;
          this.positionY = left;

          //移动当前元素
          this.odiv.style.left = left + 'px';
          this.odiv.style.top = top + 'px';
        };
        document.onmouseup = (e) => {
          document.onmousemove = null;
          document.onmouseup = null;
        };
      },
    }
  }
</script>
<style scoped>
  img {
    width: 100%;
    position: relative;
  }
</style>

您可能感兴趣的文章:

相关文章