Javascript 触摸事件:区分手指与 Apple Pencil

Javascript touch event: distinguishing finger vs. Apple Pencil

本文关键字:手指 Apple Pencil 触摸 事件 Javascript      更新时间:2023-09-26

在Mobile Safari中,有没有办法区分触摸事件是由手指还是Apple Pencil生成的?

触摸事件的TouchList对象包含有关触摸的各个点的详细信息。在众多属性中,touchType可能是您最感兴趣的,因为它包含"stylus"(Apple Pencil)或"direct"(手指)。

var body = document.querySelector('body');
body.addEventListener('touchstart', function(evt){
    // should be either "stylus" or "direct"
    console.log(evt.touches[0].touchType);
});

您还应该查看每个单独触摸的其他属性,例如forceazimuthAngle,这些属性可以为您提供有关触摸点当前设备的详细信息。

请注意,触摸界面只是W3C工作的一部分。草案,还不是官方标准 - 但是适用于iOS 10 +Safari + Apple Pencil。

您可以通过以下方式检查触摸力:

e.touches[0].force;

但它也适用于iPhone 6s上的3DTouch。

只有 iPhone 6s 上的 Apple Pencil 事件和触摸事件具有 .force

编辑

现在在iOs Safari上有touchType

e.touches[0].touchType === 'direct' // this is a finger

e.touches[0].touchType === 'stylus' // this is an Apple Pencil