如何判断用户设备
userAgent
通过浏览器navigator.userAgent判断用户设备
UAParser.js:一个用于检测当前设备的工具库,也可以用在node.js中
matchMedia
利用window.matchMedia方法判断屏幕宽度,如果小于760px视为移动设备
javascript
let isMobile = window.matchMedia("only screen and (max-width: 760px)").matches;判断当前设备游标,是否为不精确的
javascript
let isMobile = window.matchMedia("(pointer:coarse)").matches;如果设备支持鼠标和触摸的方式,则需要使用any-pointer判断
javascript
let isMobile = window.matchMedia("(any-pointer:coarse)").matches;touch
touch是移动设备特有的事件,可以通过该事件判断是否为移动设备
javascript
function isMobile() {
try {
document.createEvent("TouchEvent"); return true;
} catch(e) {
return false;
}
}