JavaScript determines what device the current device is

Determine device type

We often need to do this, display A logic on the mobile phone and display B logic on the PC. Basically, the device type is determined by identifying the browser's userAgent.

Determine whether the device is Android or IOS

In addition to distinguishing whether it is a mobile phone or a PC, many times we also need to distinguish whether the current device is Android or IOS.

 Code display

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      list-style: none;
    }

    html,
    body {
      width: 100%;
      height: 100%;
    }
  </style>
</head>

<body>
  <div id="message" style="color: red;"></div>
  <div>判断当前是移动设备还是桌面设备</div>

  <div id="msg" style="color: red;"></div>
  <div>判断当前设备是Android还是ios</div>
</body>
<script>
  // 判断是什么设备
  const isMobile = () => {
    return !!navigator.userAgent.match(
      /(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i
    );
  };
  const message = document.querySelector('#message');
  if (isMobile()) {
    message.textContent = '您正在使用移动设备。';
  } else {
    message.textContent = '您正在使用桌面设备。';
  }



  const isAndroid = () => {
    return /android/i.test(navigator.userAgent.toLowerCase());
  };
  const isIOS = () => {
    let reg = /iPhone|iPad|iPod|iOS|Macintosh/i;
    return reg.test(navigator.userAgent.toLowerCase());
  };
  const msg = document.querySelector('#msg');
  if (isAndroid()) {
    msg.textContent = '当前设备是 Android';
  } else {
    // msg.textContent = '当前设备不是 Android';
    console.log('当前设备不是 Android');
  }

  if (isIOS()) {
    msg.textContent = '当前设备是 iOS';
  } else {
    // msg.textContent = '当前设备不是 iOS';
    console.log('当前设备不是 iOS');
  }
</script>

</html>

Guess you like

Origin blog.csdn.net/m0_63873004/article/details/130501587