如何检测设备是否支持鼠标? [英] How to detect if a device has mouse support?
本文介绍了如何检测设备是否支持鼠标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前使用以下测试(从Modernizr中删除)来检测触摸支持:
I currently use the following test (taken out of Modernizr) to detect touch support:
function is_touch_device() {
var bool;
if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
bool = true;
} else {
injectElementWithStyles(['@media (',prefixes.join('touch-enabled),('),mod,')','{#modernizr{top:9px;position:absolute}}'].join(''), function(node) {
bool = node.offsetTop === 9;
});
}
return bool;
}
但是有些设备是触摸和鼠标驱动的,所以我想要一个单独的功能来检测设备是否支持鼠标.什么是进行此检查的好方法?
But some devices are both touch and mouse driven, so I want a seperate function to detect if a device has mouse support. What's a good way to do this check?
我的最终目的是能够做到这些:
Ultimately my intention is to be able to do these:
if(is_touch_device())
if(has_mouse_support())
if(is_touch_device() && has_mouse_support())
推荐答案
有就是CSS媒体!
您可以通过获取pointer
CSS媒体功能的值来检查某些设备是否具有鼠标:
You can check whether some device has a mouse by getting the value of the pointer
CSS media feature:
if (matchMedia('(pointer:fine)').matches) {
// Device has a mouse
}
因为它是CSS,所以您甚至不需要使用JavaScript:
Because it's CSS you don't even need to use JavaScript:
@media (pointer: fine) {
/* Rules for devices with mouse here */
}
这篇关于如何检测设备是否支持鼠标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文