-
Notifications
You must be signed in to change notification settings - Fork 10
Open
Description
判断用户为移动端设备的若干种方式
判断 userAgent
userAgent 返回当前浏览器的用户代理字符串,通常用于判断客户端使用的操作系统、浏览器或其他软件信息
function isMobileAgent() {
const userAgent = navigator.userAgent.toLowerCase();
return /iphone|ipad|ipod|ios|android|windows phone|blackberry|bb|playbook|opera mini|kindle|silk|fennec|mobile/.test(userAgent);
}iphone|ipad|ipod: 苹果移动设备ios: iOS 系统(一些特殊情况)android: 安卓设备windows phone: Windows Phone 设备blackberry|bb|playbook: 黑莓设备及其平板opera mini: Opera Mini 浏览器,通常用于移动设备kindle|silk: 亚马逊的 Kindle 和 Silk 浏览器fennec: Firefox 移动版浏览器mobile: 一个通用的关键字,通常出现在移动设备的用户代理字符串中
更全面的正则可参考 rustdesk/flutter/web/js/src/globals.js,代码简化如下
function isMobileAgent() {
return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent)
}使用 ismobilejs 库
ismobilejs 库对设备判断进行细分:
- apple
- android
- amazon
- windows phone
- other
同时每个设备下还区分了
- phone
- tablet
- device
import isMobile from 'ismobilejs';
const userAgent = window.navigator;
console.log(isMobile(userAgent));
console.log(isMobile(userAgent).apple);
console.log(isMobile(userAgent).android);
console.log(isMobile(userAgent).amazon);
console.log(isMobile(userAgent).windows);
console.log(isMobile(userAgent).other);判断视口宽度
一般来说设备的视口宽度小于 768px 即为移动端设备
function isMobileWidth() {
return window.innerWidth <= 768 || document.documentElement.clientWidth <= 768;
}window.innerWidth返回视口宽度(包含滚动条)document.documentElement.clientWidth返回根元素<html>的视口宽度(不包含滚动条)
判断 CSS 媒体查询结果
使用
max-width
function isMobileWidth() {
return window.matchMedia('(max-width: 768px)').matches;
}使用
any-pointer:coarse
function isMobile() {
return window.matchMedia('(pointer: coarse)').matches;
}
// OR
function isMobile() {
return window.matchMedia('(any-pointer: coarse)').matches;
}pointer: 检测主要输入设备是否拥有任意订单装置(如鼠标)any-pointer: 检测任意输入设备是否拥有任意订单装置
使用
hover: none
function isMobile() {
return window.matchMedia('(hover: none)').matches;
}
// OR
function isMobile() {
return window.matchMedia('(any-hover: none)').matches;
}hover: 检测主要输入设备是否可以悬停在元素之上来应用样式(即支持hover)any-hover: 检测任意输入设备是否可以悬停在元素之上来应用样式
集合以上判断
function isMobile() {
return window.matchMedia('(max-width: 767px), (any-pointer: coarse), (any-hover: none)').matches;
}判断是否支持触摸事件
maxTouchPoints 返回当前设备支持的最大同时触摸接触点数
function isTouchDevice() {
return 'ontouchstart' in window || navigator.maxTouchPoints > 0;
}Metadata
Metadata
Assignees
Labels
No labels