我正在开发一个 WordPress 主题,并试图将支持 Retina 的 CSS 查询合并到我的 CSS 文件中。
我想澄清一下,在我更改所有背景图片之前,我已经正确设置了媒体查询。
- 我将所有背景图片的大小都扩大了一倍,并添加了前缀
他们使用“@2x”命名约定。例如
icon-user@2x.png
。 - 我在我的代码中添加了一个 jQuery 函数,以使用
hires
的 CSS 类替换图像。 - 在我的 CSS 文档中,我有一个用于背景图片的普通 CSS 类。
普通 CSS 查询
.side-nav .arrow { background: url(../images/arrow-nav.png) no-repeat top left; width: 5px; height: 8px; display: inline-block; margin-left: 10px }
这是我为支持视网膜的设备更改 .side-nav .arrow 类的正确方法吗?声明背景大小时,我是否保持原始较小图像的大小?
/* All Retina Ready devices larger than 1.5 pixel ratio */
@media only screen and (-moz-min-device-pixel-ratio: 1.5),
only screen and (-o-min-device-pixel-ratio: 3/2),
only screen and (-webkit-min-device-pixel-ratio: 1.5),
only screen and (min-device-pixel-ratio: 1.5) {
.side-nav .arrow {
background-image:url(../images/arrow-nav@2x.png);
-webkit-background-size:5px 8px;
-moz-background-size:5px 8px;
-o-background-size:5px 8px;
background-size:5px 8px
}
}
jQuery 代码
$(function () {
if (window.devicePixelRatio == 2) {
var images = $("img.hires");
/* loop through the images and make them hi-res */
for(var i = 0; i < images.length; i++) {
/* create new image name */
var imageType = images[i].src.substr(-4);
var imageName = images[i].src.substr(0, images[i].src.length - 4);
imageName += "@2x" + imageType;
/* rename image */
images[i].src = imageName;
}
}
});
谢谢
最佳答案
只要有某种形式的缩放发生,比如当你声明
<meta name="viewport" content="width=...">
(适用于安卓/iOS/黑莓/WP8)
或
@ms-viewport {width: ... ;}
(对于非 WP8 IE10)
或者 ... 即使您什么都不声明,大多数移动设备默认情况下会自动缩放,使视口(viewport)宽度 = 980px
那么无论物理 DPI/PPI 之间的差异如何,您使用“px”声明的所有 CSS 尺寸都将以与视口(viewport)相同的比例存在
这意味着当媒体查询匹配高分辨率设备时,除了背景图片的 URL 之外,您不必更改样式类的任何内容:
@media only screen and (-moz-min-device-pixel-ratio: 1.5),
only screen and (-o-min-device-pixel-ratio: 3/2),
only screen and (-webkit-min-device-pixel-ratio: 1.5),
only screen and (min-device-pixel-ratio: 1.5),
only screen and (min-resolution: 144dpi) {
.side-nav .arrow {
background-image:url(../images/arrow-nav@2x.png);
}
}
关于image - 了解 Retina 设备 CSS 媒体查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15456436/