79 lines
2.4 KiB
JavaScript
79 lines
2.4 KiB
JavaScript
|
|
/**
|
||
|
|
* 移动端检测工具
|
||
|
|
*/
|
||
|
|
var MobileDetect = {
|
||
|
|
/**
|
||
|
|
* 检测是否为移动设备
|
||
|
|
*/
|
||
|
|
isMobile: function() {
|
||
|
|
var userAgent = navigator.userAgent.toLowerCase();
|
||
|
|
console.log('开始移动端检测,用户代理:', userAgent);
|
||
|
|
|
||
|
|
var mobileKeywords = [
|
||
|
|
'android', 'iphone', 'ipod', 'ipad', 'windows phone', 'blackberry',
|
||
|
|
'bb10', 'opera mini', 'mobile', 'nokia', 'samsung', 'htc', 'lg'
|
||
|
|
];
|
||
|
|
|
||
|
|
// 检查用户代理字符串
|
||
|
|
for (var i = 0; i < mobileKeywords.length; i++) {
|
||
|
|
if (userAgent.indexOf(mobileKeywords[i]) !== -1) {
|
||
|
|
console.log('通过关键词检测到移动设备:', mobileKeywords[i]);
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// 检查触摸支持
|
||
|
|
var hasTouch = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
|
||
|
|
if (hasTouch) {
|
||
|
|
console.log('通过触摸支持检测到移动设备');
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
|
||
|
|
// 检查屏幕宽度
|
||
|
|
var screenWidth = window.screen ? window.screen.width : window.innerWidth;
|
||
|
|
if (screenWidth <= 768) {
|
||
|
|
console.log('通过屏幕宽度检测到移动设备, 宽度:', screenWidth);
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
|
||
|
|
console.log('检测结果: 桌面设备');
|
||
|
|
return false;
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 重定向到移动端页面
|
||
|
|
*/
|
||
|
|
redirectToMobile: function(mobileUrl) {
|
||
|
|
if (this.isMobile()) {
|
||
|
|
// 避免无限重定向
|
||
|
|
var currentUrl = window.location.href;
|
||
|
|
if (currentUrl.indexOf(mobileUrl) === -1) {
|
||
|
|
window.location.href = mobileUrl;
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return false;
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 检测具体设备类型
|
||
|
|
*/
|
||
|
|
getDeviceType: function() {
|
||
|
|
var userAgent = navigator.userAgent.toLowerCase();
|
||
|
|
|
||
|
|
if (userAgent.indexOf('ipad') !== -1) {
|
||
|
|
return 'tablet';
|
||
|
|
}
|
||
|
|
if (userAgent.indexOf('iphone') !== -1 || userAgent.indexOf('ipod') !== -1) {
|
||
|
|
return 'phone';
|
||
|
|
}
|
||
|
|
if (userAgent.indexOf('android') !== -1) {
|
||
|
|
if (userAgent.indexOf('mobile') !== -1) {
|
||
|
|
return 'phone';
|
||
|
|
}
|
||
|
|
return 'tablet';
|
||
|
|
}
|
||
|
|
|
||
|
|
return this.isMobile() ? 'mobile' : 'desktop';
|
||
|
|
}
|
||
|
|
};
|