检测设备类型

在开发移动端网站时经常需要检查用户端设备类型,以便做出不同的调整。

方式一、检测手机平板和PC

 1function detectDevice() {
 2  var isMobile = false, isTablet = false, isLaptop = false;
 3  if (window.innerWidth <= 425) {
 4    isMobile = true;
 5    isTablet = false;
 6    isLaptop = false;
 7  } else if (window.innerWidth <= 768) {
 8    isMobile = false;
 9    isTablet = true;
10    isLaptop = false;
11  } else {
12    isMobile = false;
13    isTablet = false;
14    isLaptop = true;
15  }
16}
17detectDevice();

判断是否微信浏览器

1function isWeChat () {
2  const ua = navigator.userAgent.toLowerCase()
3  return ua.match(/MicroMessenger/i) == "micromessenger"
4}