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
  }

效果

相关推荐
Fan_web3 分钟前
jQuery——事件委托
开发语言·前端·javascript·css·jquery
安冬的码畜日常5 分钟前
【CSS in Depth 2 精译_044】第七章 响应式设计概述
前端·css·css3·html5·响应式设计·响应式
莹雨潇潇1 小时前
Docker 快速入门(Ubuntu版)
java·前端·docker·容器
Jiaberrr1 小时前
Element UI教程:如何将Radio单选框的圆框改为方框
前端·javascript·vue.js·ui·elementui
Tiffany_Ho2 小时前
【TypeScript】知识点梳理(三)
前端·typescript
安冬的码畜日常3 小时前
【D3.js in Action 3 精译_029】3.5 给 D3 条形图加注图表标签(上)
开发语言·前端·javascript·信息可视化·数据可视化·d3.js
太阳花ˉ3 小时前
html+css+js实现step进度条效果
javascript·css·html
小白学习日记3 小时前
【复习】HTML常用标签<table>
前端·html
程序员大金3 小时前
基于SpringBoot+Vue+MySQL的装修公司管理系统
vue.js·spring boot·mysql