Media query for devices supporting hover

后端 未结 6 1306
醉梦人生
醉梦人生 2020-12-08 04:24

I\'d like to provide separate behaviour for browsers supporting hover (e.g. desktop browsers) and ones which don\'t (e.g. touchscreen devices). Specifically I want to declar

6条回答
  •  清歌不尽
    2020-12-08 05:00

    Thanks to Dekel's comments I solved this by running the logic in JS and applying a class instead:

    e.g.

    const canHover = !(matchMedia('(hover: none)').matches);
    if(canHover) {
      document.body.classList.add('can-hover');
    }
    

    Then in the stylesheet:

    .myElement {
      background: blue;
    }
    .can-hover .myElement:hover {
      background: red;
    }
    

    I've tested this on desktop Chrome, Safari and Firefox, and iOS Safari and it works as expected.

提交回复
热议问题