js:网页屏幕尺寸小于768时,切换到移动端页面
一、前言
当分别做了PC端和移动端,pc端没做成响应式,网页屏幕尺寸小于768时,就需要切换到移动端页面。
二、代码
网页端代码:screen.js
// 设备检测与页面跳转工具
class DeviceRedirect {constructor() {this.mobilePage = 'http://cd-qj.com:10003/#/'; // 移动端页面路径:换成自己的路径this.pcPage = 'index.html'; // PC端页面路径:换成自己的路径this.breakpoint = 768; // 断点宽度this.isRedirecting = false; // 防止重复跳转}// 检测设备类型并执行跳转checkAndRedirect() {if (this.isRedirecting) return;const width = window.innerWidth;const isMobile = width < this.breakpoint;if (isMobile && !this.isMobilePage()) {this.redirectToMobile();} else if (!isMobile && this.isMobilePage()) {this.redirectToPC();}}// 跳转到移动端页面redirectToMobile() {this.isRedirecting = true;window.location.href = this.mobilePage;}// 跳转到PC端页面redirectToPC() {this.isRedirecting = true;window.location.href = this.pcPage;}// 检测当前是否在移动端页面isMobilePage() {return window.location.pathname.includes(':10003/#/');}// 初始化监听init() {// 初始检测this.checkAndRedirect();// 监听窗口大小变化(带防抖优化)let resizeTimeout;window.addEventListener('resize', () => {clearTimeout(resizeTimeout);resizeTimeout = setTimeout(() => {this.checkAndRedirect();}, 250);});}
}// 创建实例并初始化
const deviceRedirect = new DeviceRedirect();
deviceRedirect.init();// 可选:导出供其他模块使用
if (typeof module !== 'undefined' && module.exports) {module.exports = DeviceRedirect;
}用法:将screen.js引入到每个需要切换的页面即可,就可实现实时监测。
注意:如果需要pc端和移动端页面来回切换,移动端也要做监测和跳转
