JavaScript 触摸拖动切换 div
是一种常见的交互设计,允许用户通过触摸屏幕来拖动元素,从而实现页面内容的切换。这种功能通常用于移动设备上的应用或网页,以提供更直观和便捷的用户体验。
以下是一个简单的 JavaScript 示例,展示如何实现水平滑动切换 div
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Touch Drag to Switch Divs</title>
<style>
.container {
display: flex;
overflow: hidden;
width: 100%;
}
.item {
min-width: 100%;
height: 200px;
transition: transform 0.3s;
}
#item1 { background-color: red; }
#item2 { background-color: green; }
#item3 { background-color: blue; }
</style>
</head>
<body>
<div class="container" id="container">
<div class="item" id="item1"></div>
<div class="item" id="item2"></div>
<div class="item" id="item3"></div>
</div>
<script>
let startX = 0;
let currentTranslate = 0;
let prevTranslate = 0;
let animationID = 0;
const container = document.getElementById('container');
const items = document.querySelectorAll('.item');
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;
setTransform(currentTranslate);
}
function touchEnd() {
const movedBy = currentTranslate - prevTranslate;
if (movedBy < -100 && currentTranslate > -100) {
currentTranslate -= window.innerWidth;
} else if (movedBy > 100 && currentTranslate < 0) {
currentTranslate += window.innerWidth;
}
prevTranslate = currentTranslate;
setTransform(currentTranslate);
animationID = requestAnimationFrame(smoothTransition);
}
function setTransform(translate) {
container.style.transform = `translateX(${translate}px)`;
}
function smoothTransition() {
setTransform(prevTranslate);
if ((prevTranslate > -100 && currentTranslate < -100) || (prevTranslate < 0 && currentTranslate > 0)) {
cancelAnimationFrame(animationID);
} else {
animationID = requestAnimationFrame(smoothTransition);
}
}
</script>
</body>
</html>
transform
属性进行位移,因为它不会触发重绘和回流,性能更好。touchend
事件中添加逻辑,判断滑动的距离和方向,从而决定是否切换到下一个或上一个元素。通过以上方法,可以实现一个基本的触摸拖动切换 div
的功能,并解决一些常见问题。
领取专属 10元无门槛券
手把手带您无忧上云