在JavaScript中,可以通过检测用户代理(User Agent)来判断用户是否使用手机访问网站,并据此进行页面跳转。以下是一个简单的示例代码:
function isMobile() {
var userAgentInfo = navigator.userAgent;
var mobileAgents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];
var isMobileDevice = false;
for (var i = 0; i < mobileAgents.length; i++) {
if (userAgentInfo.indexOf(mobileAgents[i]) > -1) {
isMobileDevice = true;
break;
}
}
return isMobileDevice;
}
if (isMobile()) {
window.location.href = "http://m.example.com"; // 移动端页面地址
} else {
window.location.href = "http://www.example.com"; // PC端页面地址
}
用户代理(User Agent):是一个字符串,用于标识浏览器或应用程序的类型、版本以及操作系统等信息。
mobile-detect.js
)来提高兼容性。为了提高准确性和兼容性,可以使用第三方库如mobile-detect.js
:
<script src="https://cdnjs.cloudflare.com/ajax/libs/mobile-detect/1.4.5/mobile-detect.min.js"></script>
<script>
var md = new MobileDetect(window.navigator.userAgent);
if (md.mobile()) {
window.location.href = "http://m.example.com";
} else {
window.location.href = "http://www.example.com";
}
</script>
通过这种方式,可以更可靠地检测用户设备并进行相应的页面跳转。
领取专属 10元无门槛券
手把手带您无忧上云