移动端长图滑动效果(没有缓冲)

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>Titletitle>
    <style>
        html,body{width: 100%;height: 100%;overflow:hidden}
        *{  margin: 0;padding: 0}
        .main{width: 100%;height: 100%;position: relative;}
        .box{width: 300%;height: 100%;position: absolute;  top:0;left: 0;background: yellowgreen}
    style>
head>
<body>
<div class="main">
<div class="box">
    <span>1111111111111111111111111111111111111111span>
    <span>2222222222222222222222222222222222222222span>
    <span>3333333333333333333333333333333333333span>
div>
div>
body>

<script>

    var main = document.getElementsByClassName('main')[0];
    var box = document.getElementsByClassName('box')[0];
    var x1 = 0;
    var boxOffsetLeft = 0;
    var off = 0;

    //触摸开始获取鼠标位置和元素距左边距离
    main.addEventListener('touchstart', function (e) {
        off = 1;
        var e = e || event;
        x1 = e.touches[0].pageX;
        boxOffsetLeft = box.offsetLeft;

    });


    main.addEventListener('touchend', function (e) {
        off = 0;
    });


    main.addEventListener('touchmove', function (e) {
        var e = e || event;
        if (!off)return;
        var x2 = e.touches[0].pageX - x1;//鼠标滑动的距离
        box.style.left = boxOffsetLeft + x2 + 'px';//元素根据鼠标滑动距离移动
        if (box.style.left > 0 + 'px') {
            box.style.left = 0 + 'px'; //左边距离为0时不能往左滑动
        }
        else if (box.offsetLeft < -2 * window.innerWidth) {
            box.style.left = -2 * window.innerWidth + 'px';//右边最后一屏不能继续滑动
        }
    });



script>
html>

 

转载于:https://www.cnblogs.com/xiaobaibubai/p/7097776.html

你可能感兴趣的:(移动端长图滑动效果(没有缓冲))