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
  }

效果

相关推荐
Surplusx4 分钟前
运用VS Code前端开发工具完成网页头部导航栏
前端·html
小宇的天下25 分钟前
Calibre 3Dstack --每日一个命令day13【enclosure】(3-13)
服务器·前端·数据库
LongJ_Sir35 分钟前
Cesium--可拖拽气泡弹窗(Vue3版)
javascript
跟着珅聪学java1 小时前
JavaScript 中定义全局变量的教程
javascript
一只小bit1 小时前
Qt 文件:QFile 文件读写与管理教程
前端·c++·qt·gui
午安~婉1 小时前
整理知识点
前端·javascript·vue
向前V1 小时前
Flutter for OpenHarmony数独游戏App实战:底部导航栏
javascript·flutter·游戏
人道领域2 小时前
JavaWeb从入门到进阶(javaScript)
开发语言·javascript·ecmascript
军军君012 小时前
Three.js基础功能学习十二:常量与核心
前端·javascript·学习·3d·threejs·three·三维
m0_748254662 小时前
CSS AI 编程
前端·css·人工智能