如何检测用户设备是否支持光标悬停?(JS+Bootstrap实现)
检测设备是否支持悬停光标(适配2合1设备)
单纯检测触摸设备无法适配2合1设备(这类设备同时支持触摸与鼠标操作),更可靠的方式是利用CSS媒体特性hover: hover来判断设备是否具备可用于悬停的光标,以下是两种实现方案:
方案一:使用matchMedia直接查询(推荐)
通过JavaScript的window.matchMedia方法直接检测浏览器对悬停特性的支持,无需额外CSS:
function hasCursor() { return window.matchMedia('(hover: hover)').matches; } // 调用示例 if (hasCursor()) { doCode(); }
方案二:结合CSS测试元素
若需兼容更旧的浏览器,可通过创建测试元素结合媒体查询实现:
首先在样式中添加:
@media (hover: hover) { .hover-detector { display: block !important; } }
然后实现检测函数:
function hasCursor() { const detector = document.createElement('div'); detector.className = 'hover-detector'; detector.style.display = 'none'; document.body.appendChild(detector); const isSupported = window.getComputedStyle(detector).display === 'block'; document.body.removeChild(detector); return isSupported; } // 调用示例 if (hasCursor()) { doCode(); }
两种方案都能准确识别设备是否支持悬停操作,完美适配2合1设备——只要设备具备可用于悬停的光标(比如连接了鼠标),就会返回true,不受触摸功能的干扰。
内容的提问来源于stack exchange,提问作者Pixlmoon
相关产品推荐
相关产品推荐

