vue 图像拖拽、鼠标滚轮放大缩小

vue 图像拖拽、鼠标滚轮放大缩小

//页面
<img
        v-drag
        @mousewheel.prevent="scaleFun"
        :style="scaleImg"
        :src="
          dangerImgs[0]
            ? serverIp + dangerImgs[0]
            : require('@/assets/images/no-pic.png')
        "
      />
//放大、缩小
computed: {
    scaleImg: function () {
      return `transform:scale(${this.imgScale})`;
    },
  },
  methods:{
  scaleFun(e) {
      let direction = e.deltaY > 0 ? 'down' : 'up';
      if (direction === 'up') {
        // 滑轮向上滚动
        this.imgScale += 0.1;
      } else {
        // 滑轮向下滚动
        if (this.imgScale > 0) {
          this.imgScale -= 0.1;
        }
      }
    },
   }
//拖拽
 directives: {
    //注册指令
    drag: function (el) {
      let dragBox = el; //获取当前元素
      dragBox.onmousedown = (e) => {
        console.log('注册指令', dragBox);
        e.preventDefault();
        //算出鼠标相对元素的位置
        let disX = e.clientX - dragBox.offsetLeft;
        let disY = e.clientY - dragBox.offsetTop;
        document.onmousemove = (e) => {
          //用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
          e.preventDefault();
          let left = e.clientX - disX;
          let top = e.clientY - disY;
          //移动当前元素
          dragBox.style.left = left + 'px';
          dragBox.style.top = top + 'px';
        };
        document.onmouseup = (e) => {
          e.preventDefault();
          //鼠标弹起来的时候不再移动
          document.onmousemove = null;
          //预防鼠标弹起来后还会循环(即预防鼠标放上去的时候还会移动)
          document.onmouseup = null;
        };
      };
    },
  },

你可能感兴趣的:(vue,vue.js,javascript,前端)