问题描述
我正在用 HTML/CSS/JS 构建类似 Facebook 的反应系统。我正在尝试为移动用户实现与 Facebook 上类似的触摸效果。所以我想让用户通过在反应之间滑动手指来选择反应,并在他们将释放所需的反应时做出反应。为此,我正在使用 touchstart
、touchmove
和 touchend
事件。问题是我想检测用户何时将手指滑出反应以重新启动 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" 和 "mouseup" js 事件。 参考 https://api.jquery.com/mousedown/ https://api.jquery.com/mouseup/
有关更多信息,请查看以下链接。 https://api.jquery.com/category/events/