vue 实现图片的滚轮放大和拖拽功能

<template>
  <div @mousewheel="mousewheel" @mousemove="mouseMove">
    <img
      ref="image"
      :src="imageurl"
      alt=""
      @mousedown.prevent="mouseDown" @mouseup="mouseUp"
    />
  </div>
</template>
<script>
export default {
  data() {
    return {
      imageurl: "",
      img: null,
      params: {
        //用于计算图片的缩放,位置等
        zoomVal: 1,
        isDown: false,
        disX: 0,
        disY: 0,
      },
    };
  },
  created() {
    this.imageurl = this.$route.params.imageurl;
  },
  mounted() {
    this.img = this.$refs.image;

    /*另图片居中
     屏幕宽/高度减去图片宽/高度 再除以 2 
     就得出图片要移动的位置
     */
    this.img.style.left = (document.body.clientWidth - this.img.width) / 2 + "px";
    this.img.style.top = (document.body.clientHeight - this.img.heighth) / 2 + "px";
    this.img.style.right = "none";
    this.img.style.right = "none";
    this.img.style.margin = "inherit";
  },
  methods: {
    mouseUp() {
      //鼠标抬起
      this.params.isDown = false;
    },
    mouseDown(e) {
      //鼠标按下事件
      this.params.disX = e.clientX - this.img.offsetLeft;
      this.params.disY = e.clientY - this.img.offsetTop;
      //开关打开
      this.params.isDown = true;
      console.log("鼠标按下");
      //mousedown.prevent阻止默认事件,否则鼠标拖拽的时候监听不到鼠标抬起
    },
    mouseMove(e) {
      if (!this.params.isDown) return;
      this.img.style.left = e.clientX - this.params.disX + "px";
      this.img.style.top = e.clientY - this.params.disY + "px";
    },
    mousewheel(e) {
      //鼠标滚动事件
      if (e.wheelDelta || e.detail) {
        this.params.zoomVal += e.wheelDelta / 1200;
        if (this.params.zoomVal < 0.2) {
          this.params.zoomVal = 0.2;
        }
        this.img.style.transform = "scale(" + this.params.zoomVal + ")";
      }
    },
  },
};
</script>
<style scoped>
div {
  width: 100%;
  height: 100%;
  position: relative;
  overflow-x: hidden;
  overflow-y: hidden;
}
div img {
  position: absolute;
  max-height: 100%;
  max-width: 100%;
  cursor: move;
  margin:auto;
  top:0;
  bottom:0;
  left:0;
  right:0;
}

</style>

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值