Vue错误网

当前位置 »首页 » Vue

vue实现移动端div拖动效果 - Vue

本文实例为大家分享了vue实现移动端div拖动的具体代码,供大家参考,具体内容如下

手机上会偶尔用到拖动div的效果,虽然我自己还没遇到,先写一个以防万一,需要注明的是,具体实现代码是我在网上找的,但是那个代码存在一些问题,我又搜集了其他资料对其修改,达到了现在的样子,所以还是要感谢写这段代码的大神与万能的搜索引擎

1、分享代码

html代码

<template>  <div class="main">    <div ref="move_div" @touchstart="down" @touchmove="move" @touchend="end" :style="{top: top  + 'px', left: left  + 'px'}" 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加了个背景颜色

效果图

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

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

代码呢,简洁明了,你要是对touch事件有学习需求呢可以自己琢磨,要是只是要用呢,复制粘贴改一改就行了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。