移动端的一个常见的功能
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> <style> .slider-container { width: 100%; overflow: hidden; } .slider-wrapper { display: flex; width: 200%; transition: transform 0.3s ease-in-out; } img { width: 50%; height: auto; } </style> </head> <body> <div class="slider-container"> <div class="slider-wrapper"> <img src="./img/641.png" alt="Image 1"> <img src="./img/641.png" alt="Image 2"> </div> </div> <script> var container = document.querySelector('.slider-container'); var wrapper = document.querySelector('.slider-wrapper'); var images = document.querySelectorAll('.slider-wrapper img'); var imageWidth = images[0].clientWidth; var currentIndex = 0; // 监听手势滑动事件 container.addEventListener('touchstart', handleTouchStart); container.addEventListener('touchmove', handleTouchMove); container.addEventListener('touchend', handleTouchEnd); var startX = 0; var currentX = 0; var threshold = 50; // 滑动触发切换的阈值 function handleTouchStart(event) { startX = event.touches[0].clientX; } function handleTouchMove(event) { currentX = event.touches[0].clientX; var diffX = currentX - startX; // 根据手指滑动的距离实时更新图片容器的位置 wrapper.style.transform = `translateX(${-currentIndex * imageWidth + diffX}px)`; } function handleTouchEnd() { var diffX = currentX - startX; // 根据滑动的距离和阈值判断应该切换到上一张或下一张图片 if (diffX < -threshold && currentIndex < images.length - 1) { currentIndex++; } // 切换图片容器的位置到指定索引对应的图片 wrapper.style.transform = `translateX(${-currentIndex * imageWidth}px)`; // 重置滑动变量 startX = 0; currentX = 0; } </script> </body> </html>