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
  }

效果

相关推荐
互联网搬砖老肖2 小时前
React的单向数据绑定
前端·javascript·react.js
NoneCoder2 小时前
React 生命周期与 Hook 理解解析
前端·react.js·面试
盛夏绽放3 小时前
Python常用高阶函数全面解析:通俗易懂的指南
前端·windows·python
深空数字孪生4 小时前
前端性能优化:如何让网页加载更快?
前端·性能优化
阿乐今天敲代码没4 小时前
echarts实现项目进度甘特图
前端·echarts·甘特图
john_Asura4 小时前
Vue 前端全方位性能优化指南
前端·vue.js·性能优化
日晞5 小时前
深浅拷贝?
开发语言·前端·javascript
Bonnie_12155 小时前
05-jenkins学习之旅-vue前项目部署实践
vue.js·学习·jenkins
沐土Arvin6 小时前
性能优化关键:link、script和meta的正确打开方式
开发语言·前端·javascript·设计模式·性能优化·html
叶九灵不灵6 小时前
node入门:安装和npm使用
前端·npm·node.js