我有使用3dtransforms的可拖动交互的插件,但我无法弄清楚如何使其与触摸设备一起工作,我尝试将所有mousedown,mouseup,mousemove事件替换为尊重touchstart,touchend,rouchmove事件,它似乎工作,因为每次我拖动控制台打印出NaN,没有任何明显的事情,但它似乎识别触摸事件,所以我不知道为什么它不起作用。可在此处使用的桌面示例:https://jsfiddle.net/3orh783q/
(这不是像jQuery UI那样使用jQuery)
$(document).ready(function() {
//Custum draggable functionality
$.fn.draggable = function() {
var $document = $(document)
, mouse = { update: function(e) {this.x = e.pageX; this.y = e.pageY;} };
return this.each(function(){
var $elem = $(this);
$elem.bind('mousedown.drag', function(e) {
mouse.update(e);
if ( !/^(relative|absolute)$/.test($elem.css('position') ) ) {
$elem.css('position', 'relative');
}
$document.bind('mousemove.drag', function(e) {
var translateX = (parseInt(getTranslate($elem, 'x'))||0) + (e.pageX - mouse.x),
translateY = (parseInt(getTranslate($elem, 'y'))||0) + (e.pageY - mouse.y);
// $elem.css({
// left: (parseInt(getTranslate($elem, 'x'))||0) + (e.pageX - mouse.x) + 'px',
// top: (parseInt(getTranslate($elem, 'y'))||0) + (e.pageY - mouse.y) + 'px'
// });
$elem.css({
'transform': 'translate3d('+translateX+'px, '+translateY+'px, 0)',
'-webkit-transform': 'translate3d('+translateX+'px, '+translateY+'px, 0)'
});
console.log(translateX);
console.log(translateY);
mouse.update(e);
e.preventDefault();
});
$document.one('mouseup.drag', function(e) {
$document.unbind('mousemove.drag');
});
e.preventDefault();
});
});
//Get current translate values
function getTranslate(el, pos) {
var translate = '',
position = 0;
// matrix(1, 0, 0, 1, 3, 5)
if(el.css('transform')) {
translate = el.css('transform');
}
else if(el.css('-webkit-transform')) {
translate = el.css('-webkit-transform');
} else {
translate = '';
}
var result = translate.match(/\d+/g).slice(-2);
if(pos == 'x') {
position = result[0];
}
else if(pos == 'y') {
position = result[1];
}
return position;
}
}
//Initialize dragable map
$('.dragMe').draggable();
});
修改
在游戏之后,似乎pageX和pageY未定义触摸设备
答案 0 :(得分:0)
Mousemove,mousedown和mouseup在触控设备中不起作用。您必须使用touchmove
,touchstart
和touchend
进行更改。
你可以创建一个这样的对象:
if(touch) {
events['down'] = "touchstart";
events['up'] = "touchend";
events['move'] = "touchmove";
} else {
events['down'] = "mousedown";
events['up'] = "touchend";
events['move'] = "touchmove";
}
当您需要使用它时:
$elem.bind(events['down'], function(e) {
// your stuff
});