返回
让解锁更有仪式感的向右滑动动效
前端
2023-09-24 06:34:47
向右滑动动效的意义
在移动设备上,向右滑动动效是一种常见的解锁机制,它提供了直观而方便的用户体验。它不仅方便快捷,而且还能提升解锁过程的趣味性。
纯vue组件实现向右滑动动效
下面我们将使用纯vue组件来实现向右滑动解锁动效。
组件结构
<template>
<div class="unlock-container">
<div class="handle" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd">
<img :src="handleIcon" alt="handle" />
</div>
<div class="tips">{{ tips }}</div>
<div class="icon"><img src="phone.png" alt="icon" /></div>
</div>
</template>
<script>
export default {
data() {
return {
handleIcon: 'handle.png',
tips: '向右滑动解锁',
isSliding: false,
startX: 0,
startY: 0,
moveX: 0,
moveY: 0,
threshold: 20,
};
},
methods: {
handleTouchStart(e) {
this.isSliding = true;
this.startX = e.touches[0].clientX;
this.startY = e.touches[0].clientY;
this.tips = '';
},
handleTouchMove(e) {
if (!this.isSliding) return;
this.moveX = e.touches[0].clientX - this.startX;
this.moveY = e.touches[0].clientY - this.startY;
if (Math.abs(this.moveX) > Math.abs(this.moveY) && this.moveX > 0) {
e.preventDefault();
this.handle = e.target;
this.handle.style.transform = `translateX(${this.moveX}px)`;
}
},
handleTouchEnd() {
if (!this.isSliding) return;
this.isSliding = false;
if (this.moveX >= this.threshold) {
this.handle.style.transform = `translateX(${this.threshold}px)`;
// 解锁成功逻辑
} else {
this.handle.style.transform = 'translateX(0)';
this.tips = '向右滑动解锁';
}
},
},
};
</script>
<style>
.unlock-container {
position: relative;
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.handle {
width: 100px;
height: 100px;
border-radius: 50%;
background: #ccc;
position: absolute;
top: calc(50% - 50px);
left: 0;
cursor: pointer;
}
.handle img {
width: 50px;
height: 50px;
}
.tips {
position: absolute;
top: 20px;
left: calc(50% - 40px);
font-size: 20px;
color: #666;
}
.icon {
position: absolute;
top: calc(50% - 50px);
right: 0;
}
.icon img {
width: 100px;
height: 100px;
}
</style>
滑动逻辑
handleTouchStart(e) {
this.isSliding = true;
this.startX = e.touches[0].clientX;
this.startY = e.touches[0].clientY;
this.tips = '';
},
handleTouchMove(e) {
if (!this.isSliding) return;
this.moveX = e.touches[0].clientX - this.startX;
this.moveY = e.touches[0].clientY - this.startY;
if (Math.abs(this.moveX) > Math.abs(this.moveY) && this.moveX > 0) {
e.preventDefault();
this.handle = e.target;
this.handle.style.transform = `translateX(${this.moveX}px)`;
}
},
handleTouchEnd() {
if (!this.isSliding) return;
this.isSliding = false;
if (this.moveX >= this.threshold) {
this.handle.style.transform = `translateX(${this.threshold}px)`;
// 解锁成功逻辑
} else {
this.handle.style.transform = 'translateX(0)';
this.tips = '向右滑动解锁';
}
},
该滑动逻辑实现了以下功能:
- 当用户开始滑动时,禁用默认浏览器事件,并记录滑动的起始位置。
- 在滑动过程中,计算手指移动的距离,并更新滑块位置。
- 当用户松开手指时,判断滑动的距离是否超过阈值,如果超过则触发解锁成功逻辑,否则滑块返回起始位置。
结语
通过使用纯vue组件,我们实现了向右滑动解锁动效,包括中间滑动提示文字淡出、touch手机icon开始旋转等细节。此组件可以轻松集成到您的vue项目中,为用户提供直观且有趣的解锁体验。