当touchmove事件超出目标时进行检测并重新启动



我正在用HTML/CSS/JS构建类似Facebook的反应系统。我正在努力实现类似于Facebook上移动用户的触摸效果。因此,我想让用户通过在反应之间滑动手指来选择反应,并在他们释放所需反应时做出反应。为此,我使用了touchstarttouchmovetouchend事件。问题是,我想检测用户何时将手指滑出反应以重新启动touchmove事件以进行下一个反应。我能够检测到,但无法重新启动touchmove事件,因为它导致错误Uncaught TypeError: Cannot read property 'touches' of undefined。因此,最终的效果应该是当用户开始触摸";喜欢";并将手指滑动到";哈哈"并在其上释放;哈哈"而不是";喜欢";。

这是我的HTML:

<div class="reactions">
<div class="reactions_item -like">Like</div>
<div class="reactions_item -love">Love</div>
<div class="reactions_item -care">Care</div>
<div class="reactions_item -haha">Haha</div>
<div class="reactions_item -wow">Wow</div>
<div class="reactions_item -sad">Sad</div>
<div class="reactions_item -angry">Angry</div>
</div>

这是我的JS

var reaction = jQuery('.reactions_item');
var touchOffset;
reaction.on('touchstart', function(e) {
e.preventDefault();
var touchEvent = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
touchOffset = document.elementFromPoint(touchEvent.pageX,touchEvent.pageY);
console.log('touch started');
});
reaction.on('touchmove', function(e) {
e.preventDefault();
var touchEvent = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
if (touchOffset !== document.elementFromPoint(touchEvent.pageX,touchEvent.pageY)) {
reaction.off('touchmove');
reaction.trigger('touchmove');
console.log('finger is out of current element and should restart touchmove for next element');
}
});
reaction.on('click tap touchend', function(e) {
console.log('touch released and should react');
});

我建议您应该使用"mousedown"&quot;mouseup";js事件。参考https://api.jquery.com/mousedown/https://api.jquery.com/mouseup/

有关更多信息,请查看下面的链接。https://api.jquery.com/category/events/

最新更新