检测混合设备

时间:2014-05-16 18:50:05

标签: javascript modernizr feature-detection

检测和绑定支持鼠标和触控的混合设备的事件的推荐方法是什么?

例如,如果Modernizr有一个名为hybrid的测试,您可能会这样做:

var handler = null;

switch (true) {
  case (Modernizr.hybrid):
    handler = 'touchstart click';
    break;
  case (Modernizr.touch):
    handler = 'touchstart';
    break;
  default:
    handler = 'click';
    break;
}

2 个答案:

答案 0 :(得分:4)

正如@dandavis在评论中所说的那样,将它们捆绑在一起。

虽然你可能有点聪明:尽管你不知道用户是想要使用触摸还是鼠标(或键盘或其他输入设备),你可以检测不同的事件模型(指针/触摸) - 因此只绑定可能触发的事件。

每个输入设备都可以触发click个事件,因此请确保始终绑定它们并且您已被覆盖:

if ('onpointerdown' in window) {
    // Bind to Pointer Events: `pointerdown`, `pointerup`, etc
}
else {
    // Bind to mouse events: `mousedown`, `mouseup`, etc

    if ('ontouchstart' in window) {
        // Bind to Touch Events: `touchstart`, `touchend`, etc
    }
}
// Bind to keyboard events: `keydown`, `keyup`, etc if
// necessary; can be problematic though
// Always bind to `click` events

更多细节:http://www.stucox.com/blog/the-golden-pattern-for-handling-touch-input/

答案 1 :(得分:0)

不幸的是,you can't detect a touchscreen,因此,您无法检测到混合设备。

根据您的示例代码的价值,click将触发所有这些事件。 如果你提供更多关于你想要完成什么的信息,我可以建议更多的可能性。

相关问题