zoukankan      html  css  js  c++  java
  • vue移动端拖拽移动元素

    <template>
        <div
          ref="dragBox"
          style="position: fixed; left: 100px; top: 200px"
          @touchstart="touchstartHandle('dragBox', $event)"
          @touchmove="touchmoveHandle('dragBox', $event)"
        >
          可拖拽元素
        </div>
    </template>
       data() {
            return {
                coordinate: {
                    client: {},
                    elePosition: {}
                }
            }
        },
        methods: {
            touchstartHandle(refName, e) {
                let element = e.targetTouches[0]
                // 记录点击的坐标
                this.coordinate.client = {
                    x: element.clientX,
                    y: element.clientY
                }
                // 记录需要移动的元素坐标
                this.coordinate.elePosition.left = this.$refs[refName].offsetLeft
                this.coordinate.elePosition.top = this.$refs[refName].offsetTop
            },
            touchmoveHandle(refName, e) {
                let element = e.targetTouches[0]
                // 根据初始 client 位置计算移动距离(元素移动位置=元素初始位置+光标移动后的位置-光标点击时的初始位置)
                let x = this.coordinate.elePosition.left + (element.clientX - this.coordinate.client.x)
                let y = this.coordinate.elePosition.top + (element.clientY - this.coordinate.client.y)
                // 限制可移动距离,不超出可视区域
                x = x <= 0 ? 0 : x >= innerWidth - this.$refs[refName].offsetWidth ? innerWidth - this.$refs[refName].offsetWidth : x
                y = y <= 0 ? 0 : y >= innerHeight - this.$refs[refName].offsetHeight ? innerHeight - this.$refs[refName].offsetHeight : y
                // 移动当前元素
                this.$refs[refName].style.left = x + 'px'
                this.$refs[refName].style.top = y + 'px'
            }
        },
  • 相关阅读:
    特别记录:OMNET神坑
    OMNet++运行项目后,出现错误:out/clang-release//DynaPacket_m.o:(.text+0x1296): 跟着更多未定义的参考到 _Unwind_Resume
    【2021年1月4日】与父谈话总结
    Ceph架构和原理
    Mysql的InnoDB存储引擎锁机制
    MySQL 分区表
    MySQL日志之binlog、redo log、undo log
    PTA刷题记录
    [POI2015]MYJ
    Manacher初步
  • 原文地址:https://www.cnblogs.com/maxiansheng/p/12454077.html
Copyright © 2011-2022 走看看