+
104
-

uniapp中如何绝对定位元素拖拽不会导致父页面滚动?

uniapp中如何绝对定位元素拖拽不会导致父页面滚动?


网友回复

+
4
-

在 UniApp 中,要实现绝对定位元素拖拽时不导致父页面滚动,可以通过阻止触摸事件的默认行为来实现。以下是详细的实现步骤和示例代码:

实现思路绝对定位元素:将需要拖拽的元素设置为绝对定位,方便在页面中自由移动。绑定触摸事件:为元素绑定 touchstart、touchmove 和 touchend 事件,用于处理拖拽操作。阻止默认行为:在 touchmove 事件中,调用 event.preventDefault() 方法阻止页面滚动。示例代码页面结构(.vue 文件)
<template>
  <view class="container">
    <!-- 父页面内容 -->
    <view class="parent-content">
      <view v-for="i in 50" :key="i">{{ i }}</view>
    </view>
    <!-- 可拖拽的绝对定位元素 -->
    <view
      class="draggable-element"
      :style="{ left: dragX + 'px', top: dragY + 'px' }"
      @touchstart="onTouchStart"
      @touchmove="onTouchMove"
      @touchend="onTouchEnd"
    >
      可拖拽元素
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      startX: 0,
      startY: 0,
      dragX: 100, // 初始 x 坐标
      dragY: 100, // 初始 y 坐标...

点击查看剩余70%

我知道答案,我要回答