在移动端网页开发中,菜单滑动切换是一种常见的交互方式,允许用户通过手指滑动屏幕来切换不同的菜单页面。这种交互方式通常依赖于JavaScript库或框架来实现平滑的动画效果和触摸事件处理。
以下是一个使用原生JavaScript实现简单水平滑动切换菜单的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Swipe Menu</title>
<style>
.menu-container {
display: flex;
overflow: hidden;
width: 100%;
height: 100vh;
}
.menu-page {
min-width: 100%;
height: 100%;
transition: transform 0.3s ease-in-out;
}
.menu-page:nth-child(1) { background-color: red; }
.menu-page:nth-child(2) { background-color: green; }
.menu-page:nth-child(3) { background-color: blue; }
</style>
</head>
<body>
<div class="menu-container" id="menuContainer">
<div class="menu-page">Page 1</div>
<div class="menu-page">Page 2</div>
<div class="menu-page">Page 3</div>
</div>
<script>
const container = document.getElementById('menuContainer');
let startX = 0;
let currentTranslate = 0;
let prevTranslate = 0;
let animationID = 0;
let currentIndex = 0;
container.addEventListener('touchstart', touchStart);
container.addEventListener('touchmove', touchMove);
container.addEventListener('touchend', touchEnd);
function touchStart(event) {
startX = event.touches[0].clientX;
cancelAnimationFrame(animationID);
}
function touchMove(event) {
const currentX = event.touches[0].clientX;
currentTranslate = prevTranslate + currentX - startX;
}
function touchEnd() {
const movedBy = currentTranslate - prevTranslate;
if (movedBy < -100 && currentIndex < 2) currentIndex += 1;
if (movedBy > 100 && currentIndex > 0) currentIndex -= 1;
prevTranslate = currentTranslate;
setSliderPosition();
}
function setSliderPosition() {
const offset = -currentIndex * window.innerWidth;
container.style.transform = `translateX(${offset}px)`;
}
</script>
</body>
</html>
requestAnimationFrame
来处理动画。通过以上方法,可以有效实现并优化移动端菜单的滑动切换功能。
领取专属 10元无门槛券
手把手带您无忧上云