H5实现左侧小图标初始定位在那里但是可拖动位置

先看一下实现效果图:

实现代码:

<template>
  <div class="page">
    <div
      class="service_box"
      ref="dragBox"
      style="position: fixed; right: 10px; bottom: 350px; z-index: 999999;"
      @touchstart="touchstartHandle('dragBox', $event)"
      @touchmove="touchmoveHandle('dragBox', $event)"
      @touchend="touchendHandle()"
    >
      <img src="https://g.csdnimg.cn/side-toolbar/3.4/images/kefu.png" />
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      coordinate: {
        client: {},
        elePosition: {},
      },
    }
  },
  mounted() {},
  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'
    },
    touchendHandle() {},
  },
}
</script>

<style lang="less" scoped>
.page {
  width: 100%;
  height: 100%;
  .service_box {
    width: 90px;
    height: 90px;
    background: #ffffff;
    box-shadow: 0px 10px 30px 0px rgba(230, 98, 109, 0.35);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: fixed;
    bottom: 350px;
    right: 6px;
    touch-action: none;

    img {
      width: 50px;
      height: 50px;
    }
  }
}
</style>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值