上下滑动选择通常指的是在用户界面上通过滑动操作来选择不同的选项。这种交互方式常见于移动设备和触摸屏界面,提供了直观且便捷的用户体验。
以下是一个使用JavaScript和CSS实现垂直滑动选择的简单示例:
<div class="slider-container">
<div class="slider">
<div class="option">Option 1</div>
<div class="option">Option 2</div>
<div class="option">Option 3</div>
<div class="option">Option 4</div>
<div class="option">Option 5</div>
</div>
</div>.slider-container {
width: 100%;
height: 200px; /* 设置一个固定高度 */
overflow: hidden;
position: relative;
}
.slider {
display: flex;
flex-direction: column;
transition: transform 0.3s ease-in-out;
}
.option {
height: 50px; /* 每个选项的高度 */
display: flex;
align-items: center;
justify-content: center;
border-bottom: 1px solid #ccc;
}const slider = document.querySelector('.slider');
let startY = 0;
let currentTranslate = 0;
let prevTranslate = 0;
let animationID = 0;
let currentIndex = 0;
slider.addEventListener('touchstart', touchStart);
slider.addEventListener('touchmove', touchMove);
slider.addEventListener('touchend', touchEnd);
function touchStart(event) {
startY = event.touches[0].clientY;
cancelAnimationFrame(animationID);
}
function touchMove(event) {
const currentY = event.touches[0].clientY;
const diffY = currentY - startY;
currentTranslate = prevTranslate + diffY;
setSliderPosition();
}
function touchEnd() {
const movedBy = currentTranslate - prevTranslate;
if (movedBy < -100 && currentIndex < 4) currentIndex += 1;
if (movedBy > 100 && currentIndex > 0) currentIndex -= 1;
prevTranslate = currentTranslate;
currentTranslate = -currentIndex * 50; // 每个选项高度为50px
setSliderPosition();
animationID = requestAnimationFrame(smoothTransition);
}
function setSliderPosition() {
slider.style.transform = `translateY(${currentTranslate}px)`;
}
function smoothTransition() {
setSliderPosition();
if (currentTranslate !== -currentIndex * 50) {
animationID = requestAnimationFrame(smoothTransition);
}
}transform属性进行位移,因为它不会触发重绘和回流,性能更好。touchmove事件中准确计算滑动的距离,并在touchend事件中进行适当的调整和校正。通过上述示例和解决方案,可以实现一个基本的上下滑动选择功能,并解决常见的滑动不流畅和选择不准确的问题。
没有搜到相关的文章