【问题标题】:Responding to touchstart and mousedown in desktop and mobile, without sniffing响应桌面和移动设备中的 touchstart 和 mousedown,无需嗅探
【发布时间】:2018-03-31 14:40:30
【问题描述】:

所以,我有一个问题。我想响应用户按下鼠标按钮(在桌面上)或触摸 div(在移动设备上)。我正在尝试与常青浏览器兼容。这是我迄今为止尝试过的:

  • 仅收听mouseDown 事件。这适用于桌面,但如果用户拖动,则不适用于移动设备。我希望在用户触摸屏幕后立即调用处理程序,无论他们是否在此过程中移动手指。
  • 仅收听touchStart 事件。这适用于移动设备和桌面设备,但不支持触摸事件的 Edge 和 Safari 桌面设备除外。
  • 两个都听,然后preventDefault。这会导致 Chrome 移动设备上的双重处理程序调用。触摸事件似乎是被动的,以允许在移动 Chrome 上不间断滚动,因此preventDefualt 对它们没有影响。我得到的是一条警告消息,在控制台中显示 "[Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See https://www.chromestatus.com/features/5093566007214080",preventDefault 被忽略并且我的事件被调用了两次。

显然,这可以通过嗅探触摸事件来解决,但网络上充斥着关于一个人必须是device-agnostic 和it's dangerous to detect touch events before the user interacted 的自以为是的咆哮。

所以我想问题是:有没有办法在不嗅探触摸事件的情况下做我想做的事?

在我的示例 React 代码下方:

function handler(e) {
    console.log('handler called')
    e.preventDefault()
}

export default function MyElement() {
    return (
        <div
            onMouseDown={handler}
            onTouchStart={handler}
        >
        Hello
        </div>
    )
}

【问题讨论】:

    标签: javascript dom mobile touch touch-event


    【解决方案1】:

    原来是it's not yet possible in React。一种解决方法是在第一次收到touchStart 时设置一个标志。

    touchHandler = () => {
      this.useTouch = true
      this.realHandler()
    }
    
    mouseHandler = () => {
      if (this.useTouch) return
      this.realHandler()
    }
    

    需要注意的是,第一个 touchStart 可能会在拖动的情况下丢失。

    非常令人失望。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-07
      相关资源
      最近更新 更多