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 分钟前
记一个前端导出excel受限问题
前端·javascript
da_vinci_x6 分钟前
PS 生成式扩展:从 iPad 到带鱼屏,游戏立绘“全终端”适配流
前端·人工智能·游戏·ui·aigc·技术美术·游戏美术
一壶纱6 分钟前
uni-app 中配置 UnoCSS
前端·vue.js
坐吃山猪7 分钟前
Electron02-Hello
开发语言·javascript·ecmascript
步履不停_9 分钟前
告别输入密码!打造基于 VS Code 的极致远程开发工作流
前端·visual studio code
狗哥哥15 分钟前
Vue 3 企业级表格组件体系设计实战
前端
尘世中一位迷途小书童23 分钟前
JavaScript 一些小特性:让你的代码更优雅高效
前端·javascript·架构
草帽lufei25 分钟前
高强度SOLO真实业务项目
前端·ai编程·trae
1024肥宅25 分钟前
告别异地登录告警!用 GitHub Self-Hosted Runner 打造“零打扰”全栈自动化部署
前端·后端·github
GDAL27 分钟前
CSS重置样式表(Reset CSS
前端·css