【发布时间】:2013-04-29 07:24:33
【问题描述】:
我正在使用适用于 Andriod 和 Iphone 但不适用于 IE 10 Windows mobile 的 window.devicePixelRatio。有什么选择吗?
【问题讨论】:
标签: javascript internet-explorer internet-explorer-10
我正在使用适用于 Andriod 和 Iphone 但不适用于 IE 10 Windows mobile 的 window.devicePixelRatio。有什么选择吗?
【问题讨论】:
标签: javascript internet-explorer internet-explorer-10
实际上,前面的答案都不是正确的。以下所有测试均在具有 480*800 LCD 屏幕的 Lumia 520 手机上进行:
WP8/IE 移动版 10:
预期的 devicePixelRatio 为 480/320 = 1.5,可通过以下方式计算:
Math.round(screen.availWidth * screen.deviceXDPI / screen.logicalXDPI / 4) * 4 / document.body.clientWidth
(需要四舍五入才能获得有效的 LCD 屏幕尺寸)
WP8.1/IE Mobile 11:
预期的 devicePixelRatio 是(再次)480/320 = 1.5,可以通过以下方式计算:
Math.round(screen.availWidth * window.devicePixelRatio / 4) * 4 / document.body.clientWidth
因此,即使存在 window.devicePixelRatio,它也会为您提供 DOM 屏幕尺寸和 LCD 屏幕尺寸之间的比率,但是,DOM 屏幕尺寸大于可用视口尺寸。如果您想知道 CSS 像素和设备像素之间的确切比例,则必须进行上述计算。此外,这些计算在纵向模式下有效。在横向模式下使用 screen.availHeight 代替(DOM 屏幕尺寸不会随着 IE Mobile 上的方向变化而改变)。
【讨论】:
我发现在诺基亚 Lumia 1230 上,属性 window.devicePixelRatio 会返回 1,即使该值明显不正确。测试 window.screen.deviceXDPI / window.screen.logicalXDPI 返回 1.52083333。 所以先使用 window.devicePixelRatio 并不是一个好主意。
我建议如下:
function getDevicePixelRatio (){
var pixelRatio = 1; // just for safety
if('deviceXDPI' in screen){ // IE mobile or IE
pixelRatio = screen.deviceXDPI / screen.logicalXDPI;
} else if (window.hasOwnProperty('devicePixelRatio')){ // other devices
pixelRatio = window.devicePixelRatio;
}
return pixelRatio ;
}
出于某种原因,使用最好的方法来测试屏幕对象中是否存在 deviceXDPI:
if(screen.hasOwnProperty('deviceXDPI')) {// IE mobile or IE
不适用于此手机。
【讨论】:
对于桌面和移动设备的 IE 后备,请使用:
window.devicePixelRatio = window.devicePixelRatio ||
window.screen.deviceXDPI / window.screen.logicalXDPI;
【讨论】:
window.devicePixelRatio = window.devicePixelRatio ||
Math.round(window.screen.availWidth / document.documentElement.clientWidth)