ブラウザにマウスがなく、タッチのみであることを検出する 質問する

ブラウザにマウスがなく、タッチのみであることを検出する 質問する

私は、タッチ(クリックすると指で画面が隠れる)とマウス(ホバー プレビューに大きく依存)でまったく異なるインターフェイスを持つ Web アプリケーション(興味深いテキストのページがある Web サイトではない)を開発しています。ユーザーがマウスを持っていないことを検出して、適切なインターフェイスを提示するにはどうすればよいでしょうか。マウスとタッチの両方を持っている人(一部のノートブックなど)のためにスイッチを残す予定です。

ブラウザのタッチ イベント機能は、ユーザーがタッチ デバイスを使用していることを実際に意味するものではありません (たとえば、Modernizr では機能しません)。質問に正しく答えるコードは、デバイスにマウスがある場合は false を返し、それ以外の場合は true を返します。マウスとタッチを備えたデバイスの場合は、false を返します (タッチのみではありません)。

ちなみに、私のタッチ インターフェイスはキーボードのみのデバイスにも適している可能性があるため、私が検出しようとしているのはマウスの欠如です。

必要性をより明確にするために、私が実装しようとしている API は次のとおりです。

// Level 1


// The current answers provide a way to do that.
hasTouch();

// Returns true if a mouse is expected.
// Note: as explained by the OP, this is not !hasTouch()
// I don't think we have this in the answers already, that why I offer a bounty
hasMouse();

// Level 2 (I don't think it's possible, but maybe I'm wrong, so why not asking)

// callback is called when the result of "hasTouch()" changes.
listenHasTouchChanges(callback);

// callback is called when the result of "hasMouse()" changes.
listenHasMouseChanges(callback);

ベストアンサー1

2018 年現在、ブラウザにマウス (または同様の入力デバイス) があるかどうかを検出する優れた信頼性の高い方法があります。CSS4 メディアインタラクション機能これらは現在、ほぼすべての最新ブラウザ(IE 11 および特別なモバイル ブラウザを除く)でサポートされています。

W3C:

ポインター メディア機能は、マウスなどのポインティング デバイスの存在と精度を照会するために使用されます。

次のオプションを参照してください。

    /* The primary input mechanism of the device includes a 
pointing device of limited accuracy. */
    @media (pointer: coarse) { ... }
    
    /* The primary input mechanism of the device 
includes an accurate pointing device. */
    @media (pointer: fine) { ... }
    
    /* The primary input mechanism of the 
device does not include a pointing device. */
    @media (pointer: none) { ... }

    /* Primary input mechanism system can 
       hover over elements with ease */
    @media (hover: hover) { ... }
    
    /* Primary input mechanism cannot hover 
       at all or cannot conveniently hover 
       (e.g., many mobile devices emulate hovering
       when the user performs an inconvenient long tap), 
       or there is no primary pointing input mechanism */
    @media (hover: none) { ... }
    
    /* One or more available input mechanism(s) 
       can hover over elements with ease */
    @media (any-hover: hover) { ... }
    
    
    /* One or more available input mechanism(s) cannot 
       hover (or there are no pointing input mechanisms) */
    @media (any-hover: none) { ... }

メディアクエリは JS でも使用できます。

if(window.matchMedia("(any-hover: none)").matches) {
    // do something
}

関連している:

W3 ドキュメント:https://www.w3.org/TR/mediaqueries-4/#mf-interaction

ブラウザのサポート:https://caniuse.com/#search=media%20features

同様の問題:クライアントデバイスが:hoverと:focus状態をサポートしているかどうかを検出する

おすすめ記事