vue项目实现pc和移动端长图拖拽+鼠标滚动横向滑动查看

1.html代码

 <div class="card" ref="card" @wheel.prevent="rollImg">
      <img ref="imgDiv" @load="toEnd" @mousedown.prevent="drag" @touchstart.prevent="drag" class="cardImg":style="{ left: `${left}px` }" src="url" alt="">
</div>

2.script代码

export default {
  name: 'Picture',
  data() {
    return {
      left: '',
      canmove: false
    }
  },
  methods:{
    // 图片加载完成,让其走到最后
    toEnd() {
      this.$refs.imgDiv.left = -9999
      this.compare()
    },
     // 拖拽
    drag(e) {
      let img = this.$refs.imgDiv
      this.canmove = true
      let move = (e, x) => {
        if (!this.canmove) return
        this.left = e.pageX - x
        this.compare()
      }
      /* 元素到页面距离 = 鼠标到页面的距离 - 鼠标到元素的距离 */
      if (e.type == 'mousedown') {
        let x = e.pageX - img.offsetLeft
        document.addEventListener('mousemove', e => {
          move(e, x)
        })
        document.addEventListener('mouseup', () => this.canmove = false)
      } else {
        e = e.targetTouches[0]
        let x = e.pageX - img.offsetLeft
        document.addEventListener('touchmove', ev => {
          move(ev.targetTouches[0], x)
        })
        document.addEventListener('touchend', () => this.canmove = false)
      }
    },
    // 拖拽计算
    compare() {
      let img = this.$refs.imgDiv
      let card = this.$refs.card
      let min = card.offsetWidth - img.width
      let max = 0
      /* 范围公式  a ∈ [min,max],则 a 和 min 取最大值,和 max 取最小值 */
      if (this.left == '') this.left = -9999
      this.left = Math.min(Math.max(this.left, min), max)
    },
    // 鼠标滚轮横向滚动
    rollImg(e) {
      let step = e.deltaY > 0 ? 50 : -50
      this.left += step
      this.compare()
    },
  }

}

3.css代码

.card {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
 .card .cardImg {
  height: 100%;
  position: absolute;
  top: 0;
  right: 0;
  cursor: grab;
}

我的图片是进入页面定位在最右边,向左拖拽查看图片

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值