if (/Mobi|Android|iPhone/i.test(navigator.userAgent)) {
// 当前设备是移动设备
}
// 另一种写法
if (
navigator.userAgent.match(/Mobi/i) ||
navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/iPhone/i)
) {
// 当前设备是移动设备
}
- 优点是简单方便,
- 缺点是不可靠,因为用户可以修改这个字符串,让手机浏览器伪装成桌面浏览器。
window.screen
对象返回用户设备的屏幕信息,该对象的width属性是屏幕宽度(单位为像素)。
–>该方法缺点在于,如果手机横屏使用,就识别不了
if (window.screen.width < 500) {
// 当前设备是移动设备
}
window.innerWidth
返回浏览器窗口里面的网页可见部分的宽度,比较适合指定网页在不同宽度下的样式。
const getBrowserWidth = function() {
if (window.innerWidth < 768) {
return "xs";
} else if (window.innerWidth < 991) {
return "sm";
} else if (window.innerWidth < 1199) {
return "md";
} else {
return "lg";
}
};
3. window.orientation
侦测屏幕方向,手机屏幕可以随时改变方向(横屏或竖屏),桌面设备做不到
`window.orientation`属性用于获取屏幕的当前方向,只有移动设备才有这个属性,桌面设备会返回`undefined`。
--**iPhone 的 Safari 浏览器不支持该属性。**
if (typeof window.orientation !== 'undefined') {
// 当前设备是移动设备
}
4. touch 事件
手机浏览器的 DOM 元素可以通过ontouchstart属性,为touch事件指定监听函数。桌面设备没有这个属性。
function isMobile() {
return ('ontouchstart' in document.documentElement);
}
// 另一种写法
function isMobile() {
try {
document.createEvent("TouchEvent"); return true;
} catch(e) {
return false;
}
}
5. window.matchMedia()
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,就表示查询生效,当前设备是手机。