首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >防止滚动体(Matter.js)

防止滚动体(Matter.js)
EN

Stack Overflow用户
提问于 2019-07-23 17:03:18
回答 1查看 529关注 0票数 3

背景

我想取得一些成就,但这真的让我发疯了。因此,任何帮助都将不胜感激!

我已经在Matter.js中创建了一个场景,它将被放置在页面下面的容器中。我希望来访者能够与现场互动,拖放身体。但是,允许交互会造成这样的问题,即每当鼠标在画布上时,Matter.js就阻止用户滚动。

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

代码语言:javascript
复制
mouseConstraint.mouse.element.removeEventListener("mousewheel", mouseConstraint.mouse.mousewheel);
mouseConstraint.mouse.element.removeEventListener("DOMMouseScroll", mouseConstraint.mouse.mousewheel);

这使得用户可以在页面中滚动,仍然可以通过单击和拖动主体来与场景进行交互,因为删除的只是滚动事件侦听器。至少在桌面上。

问题

但是,在移动平台上,触摸事件使用户能够在页面上滚动,因此需要我从touchmovetouchstarttouchend事件侦听器中删除Matter.js中的鼠标约束。如下所示:

代码语言:javascript
复制
mouseConstraint.mouse.element.removeEventListener('touchmove', mouseConstraint.mouse.mousemove);
mouseConstraint.mouse.element.removeEventListener('touchstart', mouseConstraint.mouse.mousedown);
mouseConstraint.mouse.element.removeEventListener('touchend', mouseConstraint.mouse.mouseup);

问题就发生在这里。如果我删除了触摸事件,用户可以滚动画布,但是用户不能与场景交互,因为这需要激活触摸事件。

所以,我想知道是否有任何方法来增加触摸事件,但只允许他们在现场的某些身体上工作?我发现我可以使用mouseConstraint.body作为布尔值,以便知道是否单击/触摸了一个身体。这能在某种程度上与此作为基础吗?:

代码语言:javascript
复制
Matter.Events.on(mouseConstraint, "mousedown", function(event) {
   if (mouseConstraint.body) {
      console.log("Body clicked!");
   }        
});
EN

回答 1

Stack Overflow用户

发布于 2021-03-25 13:42:11

这就是我想出的解决办法。这并不完美,但总比什么都没有强。

代码语言:javascript
复制
 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);
      }
    }
  });

您可以侦听touch start事件并将其存储在变量中。然后,在touchend事件中,您检查一下swipe是否足够大以构成滚动,然后滚动到内容。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57169055

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档