要实现手机触屏左右滑动效果,可以使用JavaScript结合CSS来完成。以下是一个简单的示例代码,展示了如何实现这一效果:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Swipe Effect</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="swipe-container">
<div class="swipe-item">Item 1</div>
<div class="swipe-item">Item 2</div>
<div class="swipe-item">Item 3</div>
<div class="swipe-item">Item 4</div>
</div>
<script src="script.js"></script>
</body>
</html>
/* styles.css */
body, html {
margin: 0;
padding: 0;
overflow: hidden;
}
.swipe-container {
display: flex;
width: 400%; /* 假设有4个滑动项 */
transition: transform 0.3s ease-in-out;
}
.swipe-item {
flex: 1;
min-width: 100%;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
font-size: 2em;
background-color: #f0f0f0;
border-right: 1px solid #ccc;
}
// script.js
document.addEventListener('DOMContentLoaded', () => {
const container = document.querySelector('.swipe-container');
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 < 3) currentIndex += 1;
if (movedBy > 100 && currentIndex > 0) currentIndex -= 1;
prevTranslate = currentTranslate;
setSliderPosition();
}
function setSliderPosition() {
currentTranslate = -currentIndex * window.innerWidth;
container.style.transform = `translateX(${currentTranslate}px)`;
}
});
flex
布局使滑动项水平排列。touchstart
、touchmove
和touchend
事件。touchstart
事件中记录初始触摸位置。touchmove
事件中计算当前的滑动位置。touchend
事件中根据滑动的距离决定是否切换到下一个或上一个滑动项,并更新滑动位置。通过这种方式,你可以实现一个简单且高效的手机触屏左右滑动效果。
领取专属 10元无门槛券
手把手带您无忧上云