开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第23天,点击查看活动详情
一个网页如果适配多端,或者在不同的设备下显示不同的内容,就会涉及到 PC 端和移动端的区分。
1、屏幕的宽度
第一种方法就是通过获取屏幕的宽度来判断手机端和 PC 端。
window.screen:
window.screen 中的 window 可以省略
window.innerWidth:
表示浏览器窗口内部的可见部分的宽度。
页面大小发生变化,innerWidth 也随之变化:
2、navigator.userAgent
userAgent 属性是一个只读的字符串,声明了浏览器用于 HTTP 请求的用户代理头的值
console.log(navigator.userAgent)
我们来看一下打印出来的 userAgent 的值:
判断移动端的方法如下。其中,test() 方法用于检测一个字符串是否匹配某个模式。
if (/Mobi|Android|iPhone/i.test(navigator.userAgent)) {
console.log('移动端')
}
或者:
if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
console.log('iPhone/平板')
} else if (/(Android)/i.test(navigator.userAgent)) {
console.log('安卓端')
} else {
console.log('PC端')
}
如果不使用 test() 方法,还可以使用 match 方法来进行判断:
avigator.userAgent.match(/(phone|Android|Mobile)/i)
除了 userAgent 属性之外,navigator 的属性还包括:
- appCodeName —— 浏览器代号
- appName —— 浏览器名称
- appVersion —— 浏览器版本
- cookieEnabled —— 启用Cookies
- userAgent —— 用户代理
- language —— 用户代理语言
但是,这个字符串是可修改的,所以依赖 navigator.userAgent 来判断并不是可靠的。
window.orientation 屏幕方向
当设备为非手机端的时候,会返回 undefined,所以可以用来区分手机端和 PC 端。
if (window.orientation == 90 || window.orientation == -90) {
console.log("ipad、iphone竖屏;Andriod横屏")
} else if (window.orientation == 0 || window.orientation == 180) {
//ipad、iphone横屏;Andriod竖屏
}