首页
学习
活动
专区
圈层
工具
发布

js 触摸左右滑动

在 JavaScript 中实现触摸左右滑动(Swipe)功能,可以通过监听 touchstarttouchmovetouchend 事件来判断用户的滑动方向。以下是完整的实现代码和详细说明:


​1. 基础实现(纯 JavaScript)​

代码语言:javascript
代码运行次数:0
复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Touch Swipe Example</title>
    <style>
        #swipe-area {
            width: 100%;
            height: 200px;
            background-color: #f0f0f0;
            position: relative;
            overflow: hidden;
        }
        .item {
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 24px;
            color: white;
        }
        .item:nth-child(1) { background-color: #3498db; }
        .item:nth-child(2) { background-color: #e74c3c; }
        .item:nth-child(3) { background-color: #2ecc71; }
    </style>
</head>
<body>
    <div id="swipe-area">
        <div class="item">Slide 1</div>
        <div class="item">Slide 2</div>
        <div class="item">Slide 3</div>
    </div>

    <script>
        const swipeArea = document.getElementById('swipe-area');
        let startX, startY, moveX, moveY;
        let isSwiping = false;

        // 监听触摸开始
        swipeArea.addEventListener('touchstart', (e) => {
            const touch = e.touches[0];
            startX = touch.clientX;
            startY = touch.clientY;
            isSwiping = true;
        });

        // 监听触摸移动
        swipeArea.addEventListener('touchmove', (e) => {
            if (!isSwiping) return;
            const touch = e.touches[0];
            moveX = touch.clientX;
            moveY = touch.clientY;
        });

        // 监听触摸结束
        swipeArea.addEventListener('touchend', (e) => {
            if (!isSwiping) return;
            isSwiping = false;

            // 计算滑动距离和方向
            const deltaX = moveX - startX;
            const deltaY = moveY - startY;

            // 判断是否是水平滑动(忽略垂直滑动)
            if (Math.abs(deltaX) > Math.abs(deltaY)) {
                if (deltaX > 50) {
                    console.log('向右滑动');
                    // 执行向右滑动的逻辑(如切换到上一张)
                    prevSlide();
                } else if (deltaX < -50) {
                    console.log('向左滑动');
                    // 执行向左滑动的逻辑(如切换到下一张)
                    nextSlide();
                }
            }
        });

        // 切换到下一张
        function nextSlide() {
            const items = document.querySelectorAll('.item');
            const current = Array.from(items).findIndex(item => 
                window.getComputedStyle(item).opacity === '1'
            );
            if (current < items.length - 1) {
                items[current].style.opacity = '0';
                items[current + 1].style.opacity = '1';
            }
        }

        // 切换到上一张
        function prevSlide() {
            const items = document.querySelectorAll('.item');
            const current = Array.from(items).findIndex(item => 
                window.getComputedStyle(item).opacity === '1'
            );
            if (current > 0) {
                items[current].style.opacity = '0';
                items[current - 1].style.opacity = '1';
            }
        }

        // 初始化显示第一张
        document.querySelectorAll('.item')[0].style.opacity = '1';
    </script>
</body>
</html>

​2. 优化版本(支持滑动阈值、动画效果)​

代码语言:javascript
代码运行次数:0
复制
const swipeArea = document.getElementById('swipe-area');
let startX, moveX;
let isSwiping = false;

// 监听触摸开始
swipeArea.addEventListener('touchstart', (e) => {
    const touch = e.touches[0];
    startX = touch.clientX;
    isSwiping = true;
});

// 监听触摸移动
swipeArea.addEventListener('touchmove', (e) => {
    if (!isSwiping) return;
    const touch = e.touches[0];
    moveX = touch.clientX;
});

// 监听触摸结束
swipeArea.addEventListener('touchend', (e) => {
    if (!isSwiping) return;
    isSwiping = false;

    const deltaX = moveX - startX;
    const threshold = 50; // 滑动阈值(像素)

    if (Math.abs(deltaX) > threshold) {
        if (deltaX > 0) {
            console.log('向右滑动');
            prevSlide();
        } else {
            console.log('向左滑动');
            nextSlide();
        }
    }
});

// 切换到下一张(带动画)
function nextSlide() {
    const items = document.querySelectorAll('.item');
    const current = Array.from(items).findIndex(item => 
        item.style.transform === 'translateX(0%)'
    );
    
    if (current < items.length - 1) {
        items.forEach(item => item.style.transition = 'transform 0.3s ease');
        items[current].style.transform = 'translateX(-100%)';
        items[current + 1].style.transform = 'translateX(0%)';
    }
}

// 切换到上一张(带动画)
function prevSlide() {
    const items = document.querySelectorAll('.item');
    const current = Array.from(items).findIndex(item => 
        item.style.transform === 'translateX(0%)'
    );
    
    if (current > 0) {
        items.forEach(item => item.style.transition = 'transform 0.3s ease');
        items[current].style.transform = 'translateX(100%)';
        items[current - 1].style.transform = 'translateX(0%)';
    }
}

// 初始化显示第一张
document.querySelectorAll('.item')[0].style.transform = 'translateX(0%)';
document.querySelectorAll('.item').forEach((item, i) => {
    if (i > 0) item.style.transform = 'translateX(100%)';
});

​3. 使用现成库(推荐)​

如果不想手动实现,可以使用现成的库:

  1. ​Swiper.js​​(推荐) <link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css"> <script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script> <div class="swiper"> <div class="swiper-wrapper"> <div class="swiper-slide">Slide 1</div> <div class="swiper-slide">Slide 2</div> <div class="swiper-slide">Slide 3</div> </div> </div> <script> new Swiper('.swiper', { direction: 'horizontal', loop: true, pagination: { el: '.swiper-pagination', }, navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, }); </script>
  2. ​Hammer.js​​(适用于复杂手势) <script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js"></script> <script> const swipeArea = document.getElementById('swipe-area'); const hammer = new Hammer(swipeArea); hammer.on('swipeleft', () => { console.log('向左滑动'); nextSlide(); }); hammer.on('swiperight', () => { console.log('向右滑动'); prevSlide(); }); </script>
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的视频

领券