PointerEvent实现拖动滑块效果

效果展示:

代码:

<template>
  <div class="slider-box" ref="sliderBoxRef">
    <div ref="sliderRef" id="slider" @pointerdown="pointerdown" @pointerup="pointerup">滑块</div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'

const sliderRef = ref()
const sliderBoxRef = ref()
let shiftX = 0 // 鼠标指针位置距离滑块左侧的距离

const pointerdown = (e: PointerEvent) => {
  shiftX = e.clientX - sliderRef.value.getBoundingClientRect().left // 获取鼠标指针位置距离滑块左侧的距离
  sliderRef.value.setPointerCapture(e.pointerId) // 用于将特定元素指定为未来指针事件的捕获目标。
  sliderRef.value.addEventListener('pointermove', sliderMove)
}
const pointerup = (e: PointerEvent) => {
  sliderRef.value.removeEventListener('pointermove', sliderMove)
  // 注意:无需调用 releasePointerCapture,
  // 它会在 pointerup 时被自动调用
  // sliderRef.value.releasePointerCapture(e.pointerId) // 用来将鼠标指针从先前通过 setPointerCapture() 绑定的元素身上释放出来,还给鼠标指针自由。
}
const sliderMove = (e: PointerEvent) => {
  const { width: boxWidth, left: boxLeft } = sliderBoxRef.value.getBoundingClientRect()
  const { width } = sliderRef.value.getBoundingClientRect()
  // 滑块距起点位置
  let newLeft = e.clientX - shiftX - boxLeft
  // 可以滑动的最大距离
  const rightEdge = boxWidth - width
  // 设置最小滑动距离为0
  if (newLeft < 0) {
    newLeft = 0
  }
  // 设置最大滑动距离,不超出父容器
  if (newLeft > rightEdge) {
    newLeft = rightEdge
  }
  sliderRef.value.style.transform = `translate(${newLeft}px)`
}

</script>

<style lang="scss" scoped>
.slider-box {
  background-color: skyblue;
  border-radius: 10px;
}

#slider {
  width: 140px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: palevioletred;
  cursor: move;
  user-select: none;
  border-radius: 10px;
}
</style>

你可能感兴趣的:(vue3,前端)