我在div上使用jquery bind的touchstart事件。 使用setInterval我更新数字(我可以使用每次增加数量时调用setTimeout,但这是无关紧要的)。 我想在手指(触摸)移动到div之外时清除间隔。不幸的是,直到手指从屏幕上释放才会调用touchend。 移动safari或webkit似乎不支持touchleave。
所以我的问题是:关于如何模仿touchleave的任何想法?
答案 0 :(得分:3)
基于以上回答,这就是我的工作。
var $this = $('elementselector');
var fnmove = function (e) {
e.preventDefault();
e = e.originalEvent;
var touch = e.touches[0] || e.changedTouches[0];
if (!_isInBounds(touch, $this.offset(), $this.outerWidth(), $this.outerHeight())) {
$this.trigger(touch_leave_event);
$this.unbind(touch_move_event, fnmove);
};
};
$this.bind(touch_move_event, fnmove);
- inbounds功能
function _isInBounds(touch, elemposition, width, height) {
var left = elemposition.left,
right = left + width,
top = elemposition.top,
bottom = top + height,
touchX = touch.pageX,
touchY = touch.pageY;
return (touchX > left && touchX < right && touchY > top && touchY < bottom);
};
答案 1 :(得分:2)
var $this = $('elementselector');
var fnmove = function (e) {
e.preventDefault();
e = e.originalEvent;
var touch = e.touches[0] || e.changedTouches[0];
if (!_isInBounds(touch, $this.offset(), $this.outerWidth(), $this.outerHeight())) {
$this.trigger(touch_leave_event);
$this.unbind(touch_move_event, fnmove);
};
};
$this.bind(touch_move_event, fnmove);
function _isInBounds(touch, elemposition, width, height) {
var left = elemposition.left,
right = left + width,
top = elemposition.top,
bottom = top + height,
touchX = touch.pageX,
touchY = touch.pageY;
return (touchX > left && touchX < right && touchY > top && touchY < bottom);
};
对不起,简短的回答,我要离开工作了。我会回来填补空白。但你应该明白这一点。
答案 2 :(得分:0)
我发现的最佳方法是检查touchmove处理程序中接触点的位置。当创建接触点时(在touchstart上),它将被添加到名为“touches”的数组中。可以通过索引(添加接触点的顺序)访问这些接触点。然后,您可以从此点访问x和y坐标,以确定它是否仍在您正在观察的元素的范围内。假设我有一个名为“myDiv”的div,我想检测用户的手指何时被从内部拖出。
var myDiv = document.getElementById('myDiv');
myDiv.addEventListener('touchmove', function(event){
var currentElement = document.elementFromPoint(event.touches[0].clientX, event.touches[0].clientY);
if (currentElement.id !== 'myDiv'){
console.log('finger has moved outside of element');
}
}, false);
因此,当我们移动手指时,我们使用document.elementFromPoint()函数捕获当前它所在的元素,传入从触摸数组中存储的触摸中收集的x和y坐标,在索引0处(添加触摸)将被添加到索引1,2,3等的数组中。)。最后,我们检查我们的手指当前所捕获的元素是否与“myDiv”相同。如果不是,我们就知道手指已经移开了这个元素。