js judges the left and right sliding of the mobile phone

js code

$(function() {
    function judge() {
        var startx;//Let startx be a global variable in the touch event function.
        var endx;
        var el = document.getElementById('io');//Touch area.
        function cons() { //Encapsulate this event independently to ensure the execution order, so that you can access the data that should be accessed.
            if (startx > endx) { //Determine the left and right movement program
                alert("left");
            } else {
                alert("right");
            }
        }

        el.addEventListener('touchstart', function (e) {
            var touch = e.changedTouches;
            startx = touch[0].clientX;
            starty = touch[0].clientY;
        });
        el.addEventListener('touchend', function (e) {
            var touch = e.changedTouches;
            endx = touch[0].clientX;
            endy = touch[0].clientY;
            cons(); //The data collection of startx endx should be executed after the touchend event, not in the touchstart event, so that the startx and endx data generated by the two events of touchstart and touchend can be accessed. In addition, startx and endx are global in the _touch event function, so they can be accessed in this function, so you only need to pay attention to the order of event execution.
        });
    }

    judge();
})

 

html, as long as the id corresponds to it

<body>
    <div style="width: 100%;height: 3000px;background: #08c;" id="io">

    </div>
</body>

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326863454&siteId=291194637