这是此问题的后续问题: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/