js swipe不适用于智能手机

时间:2015-03-04 09:58:08

标签: javascript

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

  

在桌面上工作正常,但在智能手机上它无法正常工作。

这是我的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

提前致谢

1 个答案:

答案 0 :(得分:1)

使用专门的触摸事件: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.

的回答是什么