Javascript 检测用户是否有鼠标

Javascript detecting wether or not user has a mouse

这不是为了设计,我正在制作一个教程,我会要求用户点击或点击东西。

现在我正在使用:

("ontouchstart" in document.documentElement);

但这在带有触摸屏的笔记本电脑上失败了。

您可以使用 CSS media queries。要检测鼠标,您的查询应如下所示:

@media (hover: hover) and (pointer: fine) {
    // 'hover' means a device that supports hovering
    // 'pointer: fine' means an accurate pointing device, as opposed to limited pointing device like touchscreen (where you would use 'coarse' value
}

请注意,此查询也会检测触摸板,但不会检测智能手机、触摸屏、手写笔屏幕或其他控制器,如 Nintendo Wii、Microsoft Kinect。

到运行来自JavaScript的相同查询,你可以使用Window.matchMedia():

if (matchMedia('(hover: hover) and (pointer: fine)').matches) {
  // You code
}