vue 滑动解锁

实现代码

html

复制代码
<div class="slider-container">
      <div class="slider-bg">
        <div class="slider-progress" :style="{ transform: `translateX(${sliderPosition + 25}px)` }"></div>
      </div>
      <div
        class="slider-button"
        ref="sliderButton"
        @touchstart="onTouchStart"
        @touchmove="onTouchMove"
        @touchend="onTouchEnd"
        @mousedown="onTouchStart"
        @mousemove="onTouchMove"
        @mouseup="onTouchEnd"
        @mouseleave="onTouchEnd"
        :style="{ transform: `translateX(${sliderPosition}px)` }"
      ></div>
    </div>

js

复制代码
const sliderButton = ref(null)
const sliderPosition = ref(0)
const sliderWidth = 50 // 滑块宽度
const containerWidth = 300 // 容器宽度

let isDragging = false
let startX = 0

const onTouchStart = (e) => {
  startX = e.type === 'touchstart' ? e.touches[0].clientX : e.clientX
  isDragging = true
}

const onTouchMove = (e) => {
  if (!isDragging) return

  const moveX = e.type === 'touchmove' ? e.touches[0].clientX - startX : e.clientX - startX
  let newPosition = sliderPosition.value + moveX

  if (newPosition < 0) newPosition = 0
  if (newPosition > containerWidth - sliderWidth) newPosition = containerWidth - sliderWidth

  sliderPosition.value = newPosition

  startX = e.type === 'touchmove' ? e.touches[0].clientX : e.clientX
}

const onTouchEnd = () => {
  isDragging = false
  if (sliderPosition.value >= containerWidth - sliderWidth) {
    setTimeout(() => {
      alert('解锁成功!')
      resetSlider()
    }, 100)
  }
}

const resetSlider = () => {
  sliderPosition.value = 0
}

css

复制代码
  .slider-container {
    position: relative;
    width: 300px;
    height: 50px;
    margin: 20px;
  }

  .slider-bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: #ccc;
    border-radius: 25px;
    overflow: hidden;
  }

  .slider-progress {
    width: 100%;
    height: 100%;
    background: #4CAF50;
    transition: width 0.1s ease;
    margin-left: -100%;
  }

  .slider-button {
    position: absolute;
    top: 0;
    left: 0;
    width: 50px;
    height: 50px;
    background: #fff;
    border-radius: 25px;
    cursor: pointer;
    user-select: none
  }

效果

相关推荐
晴殇i12 分钟前
千万级点赞系统架构演进:从单机数据库到分布式集群的完整解决方案
前端·后端·面试
CDwenhuohuo13 分钟前
WebSocket 前端node启用ws调试
前端·websocket·网络协议
Mintopia41 分钟前
🤖 具身智能与 WebAIGC 的融合:未来交互技术的奇点漫谈
前端·javascript·aigc
Mintopia43 分钟前
🧠 Next.js × GraphQL Yoga × GraphiQL:交互式智能之门
前端·后端·全栈
JarvanMo1 小时前
Bitrise 自动化发布 Flutter 应用终极指南(二)
前端
『 时光荏苒 』1 小时前
网页变成PDF下载到本地
前端·javascript·pdf·网页下载成
亿元程序员1 小时前
逃离鸭科夫5人2周1个亿,我们可以做一个鸡科夫吗?
前端
十一.3662 小时前
37-38 for循环
前端·javascript·html
波诺波2 小时前
环境管理器
linux·前端·python
San30.2 小时前
深入理解浏览器渲染流程:从HTML/CSS到像素的奇妙旅程
前端·css·html