首页 前端知识 vue项目实现pc和移动端长图拖拽 鼠标滚动横向滑动查看

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

2024-06-25 23:06:34 前端知识 前端哥 863 420 我要收藏

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;
}

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

转载请注明出处或者链接地址:https://www.qianduange.cn//article/13569.html
标签
评论
发布的文章

jQuery实现简单抽奖大转盘

2024-07-01 23:07:44

jQuery思维导图

2024-07-01 23:07:43

在jQuery中添加表格行

2024-07-01 23:07:36

jquery数据类型转换

2024-07-01 23:07:36

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!