【问题标题】:How to stop scrolling only on using pen/stylus and not on finger touch如何仅在使用笔/触控笔而不是手指触摸时停止滚动
【发布时间】:2018-02-13 06:02:01
【问题描述】:

我正在开发一个网络应用程序,该应用程序需要防止使用手写笔滚动,但仍允许在用手指滑动屏幕时滚动。

我遇到的问题是只有 pointerstart 事件可以通过 e.pointerType 区分手指触摸和手写笔触摸。

但似乎无法从指针向下停止滚动,需要使用无法检测手指和手写笔/笔之间差异的 touchstart。

在 Google Keep 上,这是通过设置 css touch-events:none; 来实现的。在画布上,如果是手指触摸,则使用指针事件生成模拟平移,但这看起来很hacky。

我要实现的示例代码

canvasElement.addEventlistener("pointerdown", function(event){
  if(event.pointerType === "pen"){
    // Disable scroll - This doesn't work
    event.preventDefault();
    event.stopPropagation();
    // Start drawing stuff
    startDrawing(...);
  } else {
    // Is a touch event do nothing, let it scroll naturally
  }
});

在不模拟滚动的情况下,这是否可行?

【问题讨论】:

    标签: javascript mobile touch event-listener pointer-events


    【解决方案1】:

    我实际上想出了如何做到这一点,有人可能会认为一种可能的方法是设置 touch-action: none css 属性仅在 pointerdown 是手写笔时有条件地设置但不起作用,当 pointerdown 时设置 css 已经太迟到,滚动将在之后启动。

    我最终这样做的方式是我有一个向下指针侦听器来检测触控笔,将其存储为变量,然后触发一个 touchstart 侦听器,仅当最后一个向下指针是触控笔时才会阻止默认设置。

    var isPen = false;
    
    document.body.addEventListener("pointerdown", function(e){
      if(e.pointerType === "pen"){
        isPen = true;
        console.log("draw");
      } else {
        isPen = false;
      }
      e.preventDefault();
    }, {
      capture: true
    });
    
    document.body.addEventListener("touchstart", function(e){
      if(isPen){
         e.preventDefault();
         }
    }, {
      passive: false,
      capture: false
    });
    

    在这里试试: https://codepen.io/crfounder/pen/GQEXZM

    【讨论】:

      猜你喜欢
      • 2020-07-28
      • 1970-01-01
      • 2020-11-15
      • 1970-01-01
      • 2020-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多