vue中拖拽实例

<template>
    <div
      class="floatball iconfont icon-xiaolu-"
      id="floatball"
      @mousedown.stop="down"
      @touchstart.stop="down"
      @mousemove.stop="move"
      @touchmove.stop="move"
      :style="{top:position.y+'px', left:position.x+'px'}"
    ></div>
</template>

<script>
var dx, dy;
var screenWidth = window.screen.width - 60;
var screenHeight = window.screen.height - 60;
export default {
  data() {
    return {
      flags: false,
      position: {
        x: 300,
        y: 500,
      },
    };
  },
  methods: {
    // 实现移动端拖拽
    down(event) {
      this.flags = true;
      var touch;
      if (event.touches) {
        touch = event.touches[0];
      } else {
        touch = event;
      }
      console.log(touch.clientX,event.target.offsetLeft);
      dx = touch.clientX - event.target.offsetLeft;
      dy = touch.clientY - event.target.offsetTop;
    },
    move(event) {
      event.preventDefault()
      if (this.flags) {
        var touch;
        if (event.touches) {
          touch = event.touches[0];
        } else {
          touch = event;
        }
        // 定位滑块的位置
        this.position.x = touch.clientX - dx;
        this.position.y = touch.clientY - dy;
        // // 限制滑块超出页面
        if (this.position.x < 0) {
          this.position.x = 0;
        } else if (this.position.x > screenWidth) {
          this.position.x = screenWidth
        }
        if (this.position.y <0) {
          this.position.y = 0;
        } else if (this.position.y > screenHeight) {
          this.position.y = screenHeight
        }
      }
    },
    //鼠标释放时候的函数
    // end() {
    //   this.flags = false;
    // },
  },
};
</script>

<style lang="scss"> 
#app,
html,
body {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100%;
  background-color: #f2f3f5;
}
.floatball {
  color: white;
  height: 50px;
  width: 50px;
  padding: 5px;
  position: fixed;
  border-radius: 50%;
  background-color: rgb(29, 157, 237);
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 40px !important;
  color: #fff;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值