这是我参与11月更文挑战的第14天,活动详情查看:2021最后一次更文挑战
1、navigator.userAgent
这种方法就是分析浏览器的user agent 字符串, js 通过navigator.userAgent 属性拿到这个字符串,只要里面包含 mobi/android/iphone 等关键字,就可以认定是移动设备。 if( /Mobi|Andriod|Iphone/i.test(navigator.userAgent) ){ document.write(
<h1>navigator.userAgent 检测到移动端</h1>) }else{ document.write(<h1>navigator.userAgent 检测到 pc端</h1>) }
优点:简单, 缺点:不可靠,因为用户可以修改这个字符串,让手机浏览器伪装成桌面浏览器
stackoverflow.com/questions/1… // 此外还有一个已经被废除的 navigator.platform 属性,所有浏览器都支持,他返回一个字符串,表示用户的操作系统。
if( /iPhone/i.test(navigator.platform) ){ // HP-UX Linux i686 Linux armv7l Mac68K MacPPC MacIntel SunOS Win16 Win32 WinCE iPhone iPod iPad Android BlackBerry Opera
document.write(`<h1>navigator.platform 检测到iphone</h1>`)
}else if( /Win/i.test(navigator.platform) ){
document.write(`<h1>navigator.platform 检测到 windows</h1>`)
}
2、window.screen
window.screen 对象返回用户设备的屏幕信息,该对象的 windth 属性时屏幕宽度(单位为像素)
if( window.screen.width <500 ){ document.write("移动设备") }在这种方法中,如果屏幕宽度window.screen.width 小于500 认为是手机, 这个方法的缺点在于,如果手机横屏,就识别不了了。
另一个属性 window.innerWidth 返回浏览器窗口里面的网页可见部分的宽度,比较适合指定网页在不同宽度下的样式。
const getBrowserWinth = function () {
if( window.innerWidth < 500){
return "L"
}else if(window.innerWidth < 800){
return "XL"
}else if( window.innerWidth < 1000){
return "XXL"
}else {
return"windows"
}
}
3、window.orientation
window.orientation 这种方法时侦测屏幕方向,手机屏幕可以随时改变方向(竖屏或横屏),桌面设备做不到。 window.orientation 属性用于获取屏幕的当前方向,只有移动设备才有这个属性,桌面设备会返回 undefined。
if( typeof window.orientation !== "undefined" ){
document.write("移动设备")
}
iphone 的safari浏览器不支持该属性。
4、ontouchstart
手机浏览器的DOM可以通过 ontouchstart 属性,为touch 事件指定监听函数。桌面设备没有这个属性。
function isMobile() {
return ('ontouchstart' in documentElement)
}
另一种写法
function isMobile() {
try {
document.createEvent("TouchEvent"); return true;
} catch (e) {
return false;
}
}
5、window.matchMedia()
> 这是一种结合css来判断的方法
CSS 通过 media query(媒介查询)为网页指定响应式样式。如果某个针对手机的 media query 语句生效了,就可以认为当前设备是移动设备。 window.matchMedia()方法接受一个 CSS 的 media query 语句作为参数,判断这个语句是否生效。
let isMobile = window.matchMedia("only screen and (max-width:760px)").matches;上面示例中,window.matchMedia()的参数是一个 CSS 查询语句,表示只对屏幕宽度不超过 700 像素的设备生效。它返回一个对象,该对象的matches属性是一个布尔值。如果是true,就表示查询生效,当前设备是手机。 除了通过屏幕宽度判断,还可以通过指针的精确性判断。let isMobile = window.matchMedia("(pointer:coarse)").matches;上面示例中,CSS 语句pointer:coarse表示当前设备的指针是不精确的。由于手机不支持鼠标,只支持触摸,所以符合这个条件。有些设备支持多种指针,比如同时支持鼠标和触摸。pointer:coarse只用来判断主指针,此外还有一个any-pointer命令判断所有指针。let isMobile = window.matchMedia("(any-pointer:coarse)").matches;上面示例中,any-pointer:coarse表示所有指针里面,只要有一个指针是不精确的,就符合查询条件。