1. 主页
  2. 文档
  3. 移动之高效开发
  4. 移动端事件
  5. 4.5 幻灯片的操控部分–左右拖动

4.5 幻灯片的操控部分–左右拖动

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
    <title>4.4 幻灯片的操控部分--左右拖动</title>
    <link rel="stylesheet" href="css/slider.css">
</head>
<body>
    <div id="slider" class="slider">
        <div class="slider-item-container">
            <div class="slider-item">
                <a href="###" class="slider-link">
                    <img src="img/1.jpg" alt="slider" class="slider-img">
                </a>
            </div>
            <div class="slider-item">
                <a href="###" class="slider-link">
                    <img src="img/2.jpg" alt="slider" class="slider-img">
                </a>
            </div>
            <div class="slider-item">
                <a href="###" class="slider-link">
                    <img src="img/3.jpg" alt="slider" class="slider-img">
                </a>
            </div>
            <div class="slider-item">
                <a href="###" class="slider-link">
                    <img src="img/4.jpg" alt="slider" class="slider-img">
                </a>
            </div>
            <div class="slider-item">
                <a href="###" class="slider-link">
                    <img src="img/5.jpg" alt="slider" class="slider-img">
                </a>
            </div>
        </div>
    </div>

    <script src="js/hammer.min.js"></script>
    <script src="js/slider.js"></script>
    <script>
        var slider = new Slider(document.getElementById('slider'), {
            initIndex: 0, // 初始显示第几张幻灯片,从0开始
            speed: 300, // 幻灯片的切换速度
            hasIndicator: true // 是否需要指示器indicator
        });

        var hammer = new Hammer(slider.getItemContainer());

        hammer.on('panmove', function (ev) {
            // console.log('panmove', ev);
            var distance = ev.deltaX + slider.getDistanceByIndex(slider.getIndex());

            slider.move(distance);
        });
        hammer.on('panend', function (ev) {
            // console.log('panend', ev);
            var distance = ev.deltaX + slider.getDistanceByIndex(slider.getIndex());
            var index = getIndexByDistance(distance);
            console.log(index);
            slider.to(index);
        });

        // 根据容器的移动距离获取索引
        function getIndexByDistance(distance) {
            if (distance > 0) {
                return 0;
            } else {
                return Math.round(-distance / slider.getDistancePerSlide());
                    // 0.6 / 1 = 0.6 = 1
                    // 0.4 / 1 = 0.4 = 0
                    // 1 - 0.4 = 0.6 1
                    // 1 - 0.6 = 0.4 0
            }
        }
    </script>
</body>
</html>
这篇文章对您有用吗?

我们要如何帮助您?