vue移动端可拖拽功能

vue移动端可拖拽功能

类似手机上桌面的小气泡,可随意拖动
vue移动端可拖拽功能_第1张图片
vue移动端可拖拽功能_第2张图片
1:首先在vue的公共组件中(components)新建个组件

<!-- 拖拽滑动 -->
<template>
  <div id="default_drag_comp"
    @click="goNext"
    @touchstart="down"
    @touchmove="move"
    @touchend="end"
  >
         <a :href="'tel:' + storeItems"> <span class="iconfont icon-kefu"></span></a>
  </div>
</template>

<script>
export default {
  name: "defaultDrag",
  data() {
    return {
      flags: false,
      position: { x: 0, y: 0 },
      nx: "",
      ny: "",
      dx: "",
      dy: "",
      xPum: "",
      yPum: ""
    };
  },

  components: {},

  computed: {},

  mounted() {},

  methods: {
    goNext() {
      this.$emit("goNext");
    },
    // 实现移动端拖拽
    down() {
      let default_drag_comp = document.querySelector("#default_drag_comp");
      this.flags = true;
      var touch;
      if (event.touches) {
        touch = event.touches[0];
      } else {
        touch = event;
      }
      this.maxW = document.body.clientWidth - default_drag_comp.offsetWidth;
      this.maxH = document.body.clientHeight - default_drag_comp.offsetHeight;

      this.position.x = touch.clientX - default_drag_comp.offsetLeft;
      this.position.y = touch.clientY - default_drag_comp.offsetTop;
      this.dx = touch.clientX;
      this.dy = touch.clientY;
    },
    move(event) {
      event.preventDefault();
      let default_drag_comp = document.querySelector("#default_drag_comp");
      if (this.flags) {
        var touch;
        if (event.touches) {
          touch = event.touches[0];
        } else {
          touch = event;
        }
        this.nx = touch.clientX - this.position.x;
        this.ny = touch.clientY - this.position.y;

        if (this.nx < 0) {
          this.nx = 0;
        } else if (this.nx > this.maxW) {
          this.nx = this.maxW;
        }

        if (this.ny < 0) {
          this.ny = 0;
        } else if (this.ny >= this.maxH) {
          this.ny = this.maxH;
        }

        default_drag_comp.style.left = this.nx + "px";
        default_drag_comp.style.top = this.ny + "px";
        //阻止页面的滑动默认事件;如果碰到滑动问题,1.2 请注意是否获取到 touchmove
        document.addEventListener(
          "touchmove",
          function() {
            // event.preventDefault();
          },
          false
        );
      }
    },
    //鼠标释放时候的函数
    end() {
      this.flags = false;
    }
  }
};
</script>
<style scoped lang="scss">
#default_drag_comp {
  width: 0.8rem;
  height: 0.8rem;
  border-radius: 50%;
  border: 2px solid #ffffff;
  box-shadow: 0 0 0.4rem 2px #d3d3d3;
  background: #CBA16B;
  position: fixed;
  z-index: 1000;
  bottom: 3rem;
  right: 0.4rem;
  display: flex;
  justify-content: center;
  align-items: center;
  span {
    color: #ffffff;
    font-size: 0.4rem;
  }
}
</style>

2.在所需要这个功能的页面上引入组件
一下是vue的内容,不全,但是会的应该都明白

<drag @goNext="watchCar"/>
<script>
import drag from "@components/drag";
export default {
  name: "Index",
  components: {drag},
</script>

你可能感兴趣的:(vue,公众号)