我在 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
提前致谢
最佳答案
使用专用触摸事件:touchstart
、touchmove
、thouchend
。你必须知道你必须读取 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/