javascript - js swipe 不适用于智能手机

标签 javascript

我在 js 上编写了简单的滑动功能。

On desktop works fine everything, but on smartphones it doesn't work.

这是我的 JavaScript:

(function(){
    var project = {
        dragging: false,
        xCordinateDown: null,
        yCordinateDown: null,
        init:function(){
            var swipeObject = document.getElementById('slide');
            swipeObject.addEventListener('mousedown', this.taped);
            swipeObject.addEventListener('mouseup', this.tapedOut);
            swipeObject.addEventListener('mouseleave', this.tapedOut);
            swipeObject.addEventListener('mousemove', this.swiped);
        },
        taped:function(e){
            this.dragging = true;
            this.xCordinateDown = e.clientX;
            this.yCordinateDown = e.clientY;
        },
        tapedOut:function(){
            this.dragging = false;
            this.xCordinateDown = null;
            this.yCordinateDown = null;
            document.getElementById("slide").style.top = 0;
        },
        swiped:function(e){
            if(this.dragging){
                var xCordinate = e.clientX;
                var yCordinate = e.clientY;

                var xDifference = this.xCordinateDown - xCordinate;
                var yDifference = this.yCordinateDown - yCordinate;

                if(Math.abs(xDifference) < Math.abs(yDifference)){
                    if(yDifference < 0){

                        document.getElementById("slide").style.top = Math.abs(yDifference) + 'px';
                    }                     
                }
            }
        }
    }
    project.init();
})();
<小时/>

如何在智能手机上修复该问题? 问题出在哪里?

这里是 jsfiddle: DEMO FIDDLE

提前致谢

最佳答案

使用专用触摸事件:touchstarttouchmovethouchend。你必须知道你必须读取 TouchEvent.targetTouches 的偏移量。 :

var startCoords = null;
el.addEventListener('touchstart', function(event) {
    startCoords = [
        event.targetTouches[0].pageX,
        event.targetTouches[0].pageY,
    ];
});

并且 touchend 事件不会为您提供 targetTouches

我回答了 difference on touchstart/mousedown & touchend/mouseup is. 是什么?

关于javascript - js swipe 不适用于智能手机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28851419/

相关文章:

javascript - 可观察的http服务

javascript - jQuery 似乎没有克隆事件,而只是克隆 html/xml?

php - 动态Javascript文件换行符和回车符

javascript - 在将 DOM 元素添加到文档之前对其进行操作

javascript - 如何在 REACT 中从另一个类调用一个类中的函数

javascript - 如何移动旋转木马顶部的 react 多旋转木马自定义按钮?

javascript - 概念图网络-节点问题

javascript - 为什么 console.log(z) 会抛出 NaN?

javascript - window.location 中的百分比编码

javascript - Bootstrap 4隐藏未关闭的警报