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>

在这里插入图片描述

posted @   叫我+V  阅读(413)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2018-03-29 python 线程 进程 协程 学习
2018-03-29 ORM 关系对象映射 基础知识点
2018-03-29 django 加载静态文件(图片,js,css)
点击右上角即可分享
微信分享提示