如何在jQuery中检测一个移动设备

如何在jQuery中检测一个移动设备

我们可以使用JavaScript window.matchMedia()方法来检测基于CSS媒体查询的移动设备。这是检测移动设备的最好和最简单的方法。

语法:

window.matchMedia();

例子-1:程序在桌面上运行。

<!DOCTYPE html>
<html lang="en">
  
<head>
    <title>
      jQuery Detect Mobile Device
  </title>
</head>
  
<body>
    <script>
        if (window.matchMedia("(max-width: 767px)").matches) 
        {
            
            // The viewport is less than 768 pixels wide
            document.write("This is a mobile device.");
        } else {
            
            // The viewport is at least 768 pixels wide
            document.write("This is a tablet or desktop.");
        }
    </script>
</body>
  
</html>

输出:
如何在jQuery中检测一个移动设备?

例子-2:程序在移动设备上运行。

<!DOCTYPE html>
<html lang="en">
  
<head>
    <title>
      jQuery Detect Mobile Device
  </title>
</head>
  
<body>
    <script>
        if (window.matchMedia("(max-width: 767px)").matches)
        {
            
            // The viewport is less than 768 pixels wide
            document.write("This is a mobile device.");
        } else {
            
            // The viewport is at least 768 pixels wide
            document.write("This is a tablet or desktop.");
        }
    </script>
</body>
  
</html>

输出:
如何在jQuery中检测一个移动设备?

支持的浏览器:

  • Google Chrome
  • Mozilla Firefox
  • Opera
  • Edge
  • Safari

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程