在JavaScript中,可以通过多种方式来判断当前访问设备是PC还是手机。以下是一些常用的方法:
以下是一个综合使用上述方法的示例代码:
function isMobileDevice() {
const userAgent = navigator.userAgent || navigator.vendor || window.opera;
const mobileRegex = /Mobi|Android/i;
const isMobileUserAgent = mobileRegex.test(userAgent);
const isSmallScreen = window.innerWidth <= 768; // 假设768px以下为移动设备
const hasTouch = ('ontouchstart' in window) || (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0);
return isMobileUserAgent || isSmallScreen || hasTouch;
}
if (isMobileDevice()) {
console.log("This is a mobile device.");
} else {
console.log("This is a PC.");
}
userAgent
字符串中是否包含Mobi
或Android
,这些通常是移动设备的标识。ontouchstart
事件或通过navigator.maxTouchPoints
和navigator.msMaxTouchPoints
来判断是否支持触摸事件。通过上述方法,可以较为准确地判断当前访问设备是PC还是手机,并根据不同的设备类型进行相应的处理和优化。
领取专属 10元无门槛券
手把手带您无忧上云