javascript - 使用 JavaScript 获取相当于 "max-width: 600px"的 css

标签 javascript css

这是此问题的后续问题:Get the device width in javascript .

我想做的是在 JavaScript 中获取与 @media (max-width: 600px) 等效的 css。

accepted answer说要执行以下操作:

var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;

这仍然是正确的吗?它适用于所有设备吗?

如果正确,检查(window.innerWidth > 0)有什么意义?

我想知道它是否仍然有效。如果您查看对答案的最后评论(有 6 个赞成票),它会说:

How does this have so many upvotes? var width = (window.innerWidth > 0) ? window.innerWidth : screen.width; returns 667 on iphone 6 AND 6 Plus. This solution does not work correctly.

最佳答案

你应该能够做这样的事情:

if (matchMedia) {
  var mq = window.matchMedia("(max-width: 600px)");
  mq.addListener(WidthChange);
  WidthChange(mq);
}

function WidthChange(mq) {
  if (mq.matches) { 
     //Window width is less than or equal to 600px
  } else { 
     //Window width is greater than 600px
  }
}

关于javascript - 使用 JavaScript 获取相当于 "max-width: 600px"的 css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41642201/

相关文章:

javascript - 悬停时仅显示一个 div

javascript - 从 jQuery/Js 添加类到谷歌标记

jquery - 动画系列图像 block 彼此独立

html - Firefox 中的 CSS 怪异 - 向左浮动而不向左浮动,除非使用大宽度

javascript - 如何对已经由前进动画处理的元素应用悬停效果?

javascript - 为 jQuery slider 设置默认值并在需要时覆盖

javascript - 如何根据字母制作金字塔?

javascript - 面对鼠标事件的问题

css - 防止伪元素自己断行

html - 在基于文本的浏览器游戏中,如何在对话中制作打字机效果?