【问题标题】:Detect when touchmove event is out of target and restart it检测 touchmove 事件何时超出目标并重新启动它
【发布时间】:2021-06-08 19:23:54
【问题描述】:

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

这是我的 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');
});

【问题讨论】:

    标签: javascript jquery touch-event touchstart touchmove


    【解决方案1】:

    我建议你应该使用“mousedown”和“mouseup”js 事件。 参考https://api.jquery.com/mousedown/ https://api.jquery.com/mouseup/

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

    【讨论】:

    • 为什么我应该使用“mousedown”和“mouseup”事件?有什么好处?我只希望在触控设备上使用该功能。
    • 好吧如果你想使用“touchmove”和“touchstart”然后像这样使用 var reaction = jQuery('.reactions_item'); react.addEventListener('touchstart', event => { // 触摸事件开始 })
    猜你喜欢
    • 2015-05-10
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多