【问题标题】:Detect if website is open in mobile without CSS [duplicate]检测网站是否在没有 CSS 的情况下在移动设备中打开 [重复]
【发布时间】:2022-11-22 09:34:21
【问题描述】:

我找不到在 JavaScript 中获取打开我的网站的设备的方法。

我想要这样的东西:

if ( website.size < 768px) {
  //do something for mobile
}

我知道我可以在 CSS 中使用媒体查询,但我想使用 JS,我很好奇如果没有 CSS 是否可行。

window.matchMediawindow.width 似乎不起作用,因为它们占了我窗口的大小。

与相关问题不同的是,本案例是制作一个响应式网站。因此,相关答案无法解决用户在计算机中调整窗口大小的情况。

【问题讨论】:

标签: javascript responsive mobile-website


【解决方案1】:

你不应该真的依赖视口宽度来知道用户是否在移动设备上,因为计算机用户可以在访问网站之前调整浏览器窗口的大小来欺骗你。

您可以在 JavaScript 中使用 navigator.userAgent 来了解他们的设备。

我找到了一个很酷的正则表达式,它使用 navigator.userAgent 属性检测用户是否在移动设备上。

if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){
  // true for mobile device
  document.write("mobile device");
}else{
  // false for not mobile device
  document.write("not mobile device");
}

它在 navigator.userAgent 属性上使用正则表达式检查所有主流移动客户端,如果匹配则返回 true,否则返回 false。

Learn more about navigator.userAgent

【讨论】:

  • 感谢您的回答!这似乎是很多人针对此问题使用的解决方案,但如果用户调整窗口大小,这对响应式网站来说不是问题,因此我们可以将此答案用于所有移动设备stackoverflow.com/questions/1248081/…(由@IT goldman 共享)
  • @AxelG 同意!!
【解决方案2】:

所以,他们有很多方法来解决这个问题

  • navigator.userAgent with Regex,如果你不希望用户像@Stranger 所说的那样通过更改窗口大小来欺骗你在浏览器上的最佳方式(相关答案Detecting a mobile browser)。

  • 使用它来获取网站的宽度和高度:(有关此 answer 的更多信息,由 @IT goldman 共享)

const vw = Math.max(
  document.documentElement.clientWidth || 0,
  window.innerWidth || 0
);
const vh = Math.max(
  document.documentElement.clientHeight || 0,
  window.innerHeight || 0
);

【讨论】:

    猜你喜欢
    • 2016-04-24
    • 2018-02-12
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    • 2012-12-17
    相关资源
    最近更新 更多