max-device-width是否指向document.body.clientWidth?

Jak*_*son 10 javascript css css3 media-queries responsive-design

在媒体的质疑,我已经看到了max-width,min-width, max-device-widthmin-device-widthorientation.

从JavaScript的角度来看,这些指的是document.body.clientWidth什么?还是window.outerWidth?我也看到了document.body.offsetWidth.

是否有资源列出所有有效的css媒体查询参数以及与之匹配的JavaScript属性?

Gio*_*ona 12

因此,您需要一个与JavaScript等效的所有有效css媒体查询参数的列表.

让我们尝试这样做,依靠 媒体查询W3C规范.


媒体类型

似乎不可能直接使用JavaScript属性/方法检索媒体类型(屏幕,打印等),因此您必须依赖于变通方法,脚本或插件.

我发现:

  1. matchMedia polyfill似乎是最好的解决方案(由Modernizr和Respond.js使用)
  2. CSS媒体检测脚本(似乎很老)
  3. jMediaType(仍然依赖于CSS)

媒体功能(可直接检测)

宽度

window.innerWidth/ document.body.clientWidth/ document.documentElement.clientWidth(见下文)

高度

window.innerHeight/ document.body.clientHeight/ document.documentElement.clientHeight(见下文)

3.设备宽度

screen.width

4.设备高度

screen.height

5.方向

window.orientation (见下文)

6.颜色

screen.colorDepth

7.决议

screen.pixelDepth/ window.devicePixelRatio(见下文)


媒体功能(间接检测)

宽度/高度

鉴于浏览器之间的差异,您需要一个函数来获取widthheight.前段时间我发现这个跨浏览器的代码片段(不记得在哪里):

var w=window,d=document,e=d.documentElement,g=d.getElementsByTagName('body')[0];

var width = w.innerWidth||e.clientWidth||g.clientWidth;

var height = w.innerHeight||e.clientHeight||g.clientHeight;
Run Code Online (Sandbox Code Playgroud)

纵横比

"宽度"媒体要素的值与"高度"媒体要素的值的比率

width/ height(见上文)

3.设备纵横比

'device-width'的值与'device-height'的值的比率

screen.width/screen.height

决议

输出设备的像素密度.'dpi'和'dpcm'单位描述输出设备的分辨率,即设备像素的密度.

因此,许多人认为不是屏幕尺寸(宽度x高度)!

var resolution = window.devicePixelRatio||screen.pixelDepth||screen.colorDepth;
Run Code Online (Sandbox Code Playgroud)

screen.pixelDepth仅适用于Firefox,您可以在quirksmode.org上找到window.devicePixelRatio兼容性.

在这里,我读到这screen.colorDepth可以作为后备.

单色

单色帧缓冲器中每像素的位数.如果设备不是单色设备,则输出设备值将为0

if ( screen.colorDepth == 2) {
    var monochrome = /* retrieve resolution here, see above */;
}else{
    var monochrome = 0;
}
Run Code Online (Sandbox Code Playgroud)

6.方向

当'height'媒体特征的值大于或等于'width'媒体特征的值时,它是'portrait'.否则'方向'是'风景'.

if ( width > height ) {
    var orientation = 'landscape';
}else{
    var orientation  = 'potrait';
}
Run Code Online (Sandbox Code Playgroud)

window.orientation所有浏览器都不支持该属性,并且它返回一个数值,因此它与W3C所预期的方向没有直接关系.有关详细信息,请在SO上查看此答案.


媒体功能(不可检测)

我找不到用JavaScript检测以下媒体功能的方法(我认为不可能):

  • 颜色索引
  • 扫描

更有趣的东西

  • screen.availHeight =屏幕高度减去界面功能(例如任务栏)
  • screen.availWidth =屏幕宽度减去界面功能(例如任务栏)
  • 要使用JavaScript模拟媒体查询,可以使用Modernizr的mq()方法,但请注意:如果浏览器不支持媒体查询,则根本不执行代码将始终返回false.

来源

  1. 宽度/高度:http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
  2. 设备宽度/高度:http://responsejs.com/labs/dimensions/
  3. 方向:使用JavaScript检测浏览器中Android手机的旋转
  4. 分辨率和颜色相关的东西:http://www.javascriptkit.com/howto/newtech3.shtml
  5. 单色:Javascript:检测单色显示
  6. 像素比率:http://www.quirksmode.org/blog/archives/2012/06/devicepixelrati.html