如何获取媒体查询中使用的值,例如设备宽度 [英] How to get the values that are used in media queries, e.g. device-width

查看:667
本文介绍了如何获取媒体查询中使用的值,例如设备宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解在CSS中使用@media查询,例如当浏览器的窗口大于一定数量时应用规则.

I understand using @media queries in CSS, e.g. to apply rules when the browser's window is larger than a certain amount.

我知道我也可以在Javascript中使用window.matchMedia()来确定某个特定查询是否匹配.

I understand that I can also use window.matchMedia() in Javascript to figure out if a particular query matches.

但是我如何才能实际获取正在使用的媒体的当前值?

But how can I actually get the current values of the media that are being used?

例如如果我想访问media的值(例如screentv ...),orientationmonochromedevice-widthwidth或其他

e.g. If I wanted to access the values for media (e.g. screen, tv...), orientation, monochrome, device-width or width or other Media Features Are these accessible through the DOM somewhere?

推荐答案

正如@abhitalks在评论中所说,不可能从DOM中获取这些值.

As @abhitalks said in the comments, it's not possible to get these values from the DOM.

这是我的解决方法.

对于具有少量已知值的简单事物,您可以一次使用window.matchMedia()进行测试.

For simple things with a small set of known values you can test those with window.matchMedia() one at a time.

对于在查询中支持min-前缀的数字事物,例如device-width您可以执行以下操作:

For numeric things that support the min- prefix in a query, e.g. device-width you can do something like this:

var ls, l=0, h=8192, c=parseInt((l+h)/2), i=20;
while (i > 0 && (c - l >1) && (h - c>1)) {
  i--; // Shouldn't take more than 13 guesses, but in case of bugs!
  if (window.matchMedia('(min-device-width: ' + c + 'px)').matches) {
    l=c; ls=0;
  } else {
    h=c; ls=1;
  }
  c = parseInt((h+l)/2);
}
c -= ls;
alert("Device width is: ", c);

codepen演示

这篇关于如何获取媒体查询中使用的值,例如设备宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆