javascript - 防止在 body 上滚动(Matter.js)

背景

我正在努力取得一些成就,但这真的让我发疯。因此,我们将不胜感激!

我在 Matter.js 中创建了一个场景,该场景将放置在页面下方的容器中。我希望访问者能够与场景交互,拖放 body 。但是允许交互会产生问题,即 Matter.js 会阻止用户在鼠标悬停在 Canvas 上时滚动。

因此,为了解决这个问题,我使用了以下代码:

mouseConstraint.mouse.element.removeEventListener("mousewheel", mouseConstraint.mouse.mousewheel);
mouseConstraint.mouse.element.removeEventListener("DOMMouseScroll", mouseConstraint.mouse.mousewheel);

这使得用户可以滚动页面并仍然能够通过单击和拖动主体与场景进行交互,因为只有滚动事件监听器被删除了。至少在桌面上。

问题

但是,在移动设备上,触摸事件是使用户可以在页面上滚动的事件,因此这需要我也删除 touchmovetouchstarttouchend 来自 Matter.js 中鼠标约束的事件监听器。像这样:

mouseConstraint.mouse.element.removeEventListener('touchmove', mouseConstraint.mouse.mousemove);
mouseConstraint.mouse.element.removeEventListener('touchstart', mouseConstraint.mouse.mousedown);
mouseConstraint.mouse.element.removeEventListener('touchend', mouseConstraint.mouse.mouseup);

这就是问题发生的地方。如果我删除触摸事件,用户可以在 Canvas 上滚动,但用户无法与场景交互,因为这需要激活触摸事件。

所以我想知道是否有任何方法可以添加触摸事件但只允许它们对场景中的某些物体起作用?我发现我可以将 mouseConstraint.body 用作 bool 值,以了解是否单击/触摸了某个主体。可以以此为基础以某种方式使用它吗?:

Matter.Events.on(mouseConstraint, "mousedown", function(event) {
   if (mouseConstraint.body) {
      console.log("Body clicked!");
   }        
});

最佳答案

这是我想出的解决方案。它并不完美,但聊胜于无。

 let touchStart;
  mouseConstraint.mouse.element.addEventListener('touchstart', (event) => {
    if (!mouseConstraint.body) {
      touchStart = event;
    }
  });

  mouseConstraint.mouse.element.addEventListener('touchend', (event) => {
    if (!mouseConstraint.body) {
      const startY = touchStart.changedTouches[0].clientY;
      const endY = event.changedTouches[0].clientY;
      const delta = Math.abs(startY - endY);

      if (delta > 80) {
        window.scrollTo(0, 600);
      }
    }
  });

您监听触摸启动事件并将其存储在一个变量中。然后在 touchend 事件中检查滑动是否足够大以构成滚动,然后滚动到内容。

https://stackoverflow.com/questions/57169055/

相关文章:

firebase - 我应该使用 Firebase 动态链接而不是通用链接和应用链接吗?

c# - Process.Start 无法正确运行批处理文件

swift - 如何使用 AVAudioEngine 在同一时间更改音调和速率

node.js - TransferHttpCacheModule 不会阻止 Angular 8 中

node.js - 如何在模块加载到 NodeJS 之前获取和使用 Secret Manager 值

amazon-web-services - 使用 aws sts assume-role 配置 AW

javascript - 使用 axios 向服务器发出请求会卡住 React Native 应用程

angular - ionic 4 : Ion-checkbox checked not updat

reactjs - 使用重新选择选择器时无法提供/测试传奇

php - 在电子邮件中添加 PhpSpreadsheet 附件