js 实现pc和移动端设备识别精准互跳

js yekong 288℃

js 实现pc和移动端设备识别跳转,移动端和pc端有很多页面 pc目录是根目录,移动端目录是/m 目录

要实现在 PC 和移动端设备之间准确进行页面互跳,可以使用以下 JavaScript 代码来进行设备识别和跳转:

// 检测设备类型
function detectDeviceType() {
  const userAgent = navigator.userAgent;
  const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent);
  
  return isMobile ? 'mobile' : 'pc';
}

// 构建目标页面 URL
function buildTargetURL(deviceType, currentPath) {
  let targetURL = '';
  
  if (deviceType === 'mobile') {
    // 移动端设备,跳转到移动端目录下
    targetURL = '/m' + currentPath;
  } else {
    // PC 设备,保持原始路径不变
    targetURL = currentPath;
  }
  
  return targetURL;
}

// 进行设备识别和跳转
function redirectBasedOnDevice() {
  const deviceType = detectDeviceType();
  const currentPath = window.location.pathname;
  const targetURL = buildTargetURL(deviceType, currentPath);
  
  // 跳转到目标页面
  window.location.href = targetURL;
}

// 调用函数进行设备识别和跳转
redirectBasedOnDevice();

以上代码中,首先使用 detectDeviceType 函数检测当前设备类型是移动端还是 PC 端。然后,使用 buildTargetURL 函数根据设备类型构建目标页面的 URL,即移动端设备会在原始路径前添加 /m,而 PC 设备则保持原始路径不变。最后,通过将 window.location.href 设置为目标 URL,进行页面跳转。

请确保你的移动端页面位于 /m 目录下,且与 PC 端页面的路径保持一致,以便在跳转时能够准确找到对应的页面。

注意:上述代码假设移动端页面和 PC 端页面在同一域名下,并且文件名一致,只是路径有所区别。如果有特殊情况,请根据实际情况进行相应的调整。

喜欢 (0)