使用css中transform或拽加普通拖拽demo

a6a7e2bb3748ab4df17ab9daab3fd3bf记录一下拖拽

<template>
  <div class="container">
    <div
      class="draggable"
      :style="{ transform: `translate(${position.x}px, ${position.y}px)` }"
      @touchstart.passive="startDrag"
      @touchmove="drag"
      @touchend="endDrag"
    ></div>
  </div>
</template>
<script setup>
import { ref } from 'vue';
const position = ref({ x: 300, y: 400 })
let dragging = ref(false)
let offset = { x: 0, y: 0 }
const startDrag = (event) => {
  dragging.value = true
  offset.x = event.changedTouches[0].clientX - position.value.x
  offset.y = event.changedTouches[0].clientY - position.value.y
}

const drag = (event) => {
  if (dragging.value) {
    event.preventDefault()
    let x = event.changedTouches[0].clientX - offset.x
    let y = event.changedTouches[0].clientY - offset.y
    const maxWidth = window.innerWidth - 50
    const maxHeight = window.innerHeight - 50
    if (x < 0) x = 0
    if (y < 0) y = 0
    if (x > maxWidth) x = maxWidth
    if (y > maxHeight) y = maxHeight
    position.value = { x, y }
  }
}

const endDrag = () => {
  dragging.value = false
}
</script>

<style scoped lang="less">
.draggable {
  width: 50px;
  height: 50px;
  background: #000;
  position: absolute;
  z-index: 8;
}
</style>

使用let-top方法

<template>
  <div class="container">
    <button 
      class="draggable" 
      :style="{ top: `${position.y}px`, left: `${position.x}px` }" 
      @touchstart.passive="startDrag" 
      @touchmove="drag" 
      @touchend="endDrag"
    >
      移动
    </button>
  </div>
</template>

<script setup>
// touchstart 指触摸屏幕的时候触发
// touchmove  滑动的时候连续地触发
// touchend   屏幕上离开的时候触发
import { ref } from 'vue';

const position = ref({ x: 300, y: 200 });
let dragging = ref(false);

const startDrag = (event) => {
  console.log(event.changedTouches[0].clientX,event.changedTouches[0].clientY)
  dragging.value = true;
};

const drag = (event) => {
  if (dragging.value) {
    event.preventDefault(); // 阻止默认事件
    let x = event.changedTouches[0].clientX;
    let y = event.changedTouches[0].clientY;
    const maxWidth = window.innerWidth - 50;  // 50 是元素的宽度
    const maxHeight = window.innerHeight - 50;  // 50 是元素的高度
       // 限制 x 和 y 不超过页面的边界
    if (x < 0) x = 0;
    if (y < 0) y = 0;
    if (x > maxWidth) x = maxWidth;
    if (y > maxHeight) y = maxHeight;
    position.value = { x, y };
  }
};

const endDrag = () => {
  dragging.value = false;
};
</script>

 

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容