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
  }

效果

相关推荐
wkj0012 小时前
vue中 js-cookie 用法
前端·javascript·vue.js
GoldKey6 小时前
gcc 源码阅读---语法树
linux·前端·windows
Xf3n1an7 小时前
html语法
前端·html
张拭心7 小时前
亚马逊 AI IDE Kiro “狙击”Cursor?实测心得
前端·ai编程
漠月瑾-西安7 小时前
如何在 React + TypeScript 中实现 JSON 格式化功能
javascript·jst实现json格式化
烛阴7 小时前
为什么你的Python项目总是混乱?层级包构建全解析
前端·python
止观止8 小时前
React响应式组件范式:从类组件到Hooks
javascript·react.js·ecmascript
@大迁世界8 小时前
React 及其生态新闻 — 2025年6月
前端·javascript·react.js·前端框架·ecmascript
LJianK18 小时前
Java和JavaScript的&&和||
java·javascript·python
红尘散仙9 小时前
Rust 终端 UI 开发新玩法:用 Ratatui Kit 轻松打造高颜值 CLI
前端·后端·rust