温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

vue怎么实现移动端div拖动效果

发布时间:2022-03-03 17:20:21 来源:亿速云 阅读:297 作者:iii 栏目:开发技术

本文小编为大家详细介绍“vue怎么实现移动端div拖动效果”,内容详细,步骤清晰,细节处理妥当,希望这篇“vue怎么实现移动端div拖动效果”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

1、分享代码

html代码

<template>
  <div class="main">
    <div ref="move_div" @touchstart="down" @touchmove="move" @touchend="end" : class="drag_area"></div>
  </div>
</template>

极其简单的结构,毕竟只是个DEMO

SCSS代码

.main{
    background-color: brown;
    height: -webkit-fill-available;
    .drag_area{
      width: 10vw;
      height: 10vw;
      background-color: dodgerblue;
      position: absolute;
      top: 0;
      left: 0;
    }
  }

为了截图显眼,特地给main加了个背景颜色

效果图

vue怎么实现移动端div拖动效果

效果呢,就是你可以在屏幕范围内自由拖动蓝色色块,不过超出屏幕区域我特意做了限制,不需要限制的可以自己改

JS代码

export default {
  name: 'drag',
  data () {
    return {
      flags: false,
      position: {x: 0, y: 0, left: 0, top: 0},
      top: 0,
      left: 0,
      width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
      height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
    }
  },
  methods: {
    down () { // 拖动开始的操作
      this.flags = true
      const refs = this.$refs.move_div.getBoundingClientRect()
      let touch = event
      if (event.touches) {
        touch = event.touches[0]
      }
      this.position.x = touch.clientX
      this.position.y = touch.clientY
      this.position.left = refs.left
      this.position.top = refs.top
    },
    move () { // 拖动中的操作
      if (this.flags) {
        let touch = event
        if (event.touches) {
          touch = event.touches[0]
        }
        const xPum = this.position.left + touch.clientX - this.position.x
        const yPum = this.position.top + touch.clientY - this.position.y
        this.left = xPum
        this.top = yPum
        this.banOut()
        // 阻止页面的滑动默认事件
        document.addEventListener('touchmove', function () {
          event.preventDefault()
        }, {passive: false})
      }
    },
    end () { // 拖动结束的操作
      this.flags = false
      this.banOut()
    },
    banOut () { // 避免拖动出界的限制
      const refs = this.$refs.move_div.getBoundingClientRect()
      if (this.left < 0) {
        this.left = 0
      } else if (this.left > this.width - refs.width) {
        this.left = this.width - refs.width
      }
      if (this.top < 0) {
        this.top = 0
      } else if (this.top > this.height - refs.height) {
        this.top = this.height - refs.height
      }
    }
  }
}

读到这里,这篇“vue怎么实现移动端div拖动效果”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI