1. 程式人生 > >關於前端Retina 屏幕兼容和基於Retina 屏幕兼容的雪碧圖技巧

關於前端Retina 屏幕兼容和基於Retina 屏幕兼容的雪碧圖技巧

com 兩張 include 很好 做的 log 項目 only alt

由於蘋果電腦的普及,所以Retina 屏幕兼容越來越重要,在普通屏幕上正常的背景,在Retina 屏幕上都會發虛。

首先新建一個scss文件,起名為utils.scss ,在文件中寫入下面代碼:

/* Retina 屏幕兼容 */
@mixin ratio(){
@media only screen and (-webkit-min-device-pixel-ratio: 1.5){
@content;
}
@media only screen and (min--moz-device-pixel-ratio: 1.5){
@content;
}
@media only screen and (min-device-pixel-ratio: 1.5){
@content;
}
@media only screen and (-o-min-device-pixel-ratio:3/2){
@content;
}
}
@mixin ratioBackground($bgcolor:transparent,$url:‘‘,$size:contain,$x: 0px,$y: 0px ){
@media only screen and (-webkit-min-device-pixel-ratio: 1.5){
background:$bgcolor url($url) $x $y no-repeat;
background-size:$size;
}
@media only screen and (min--moz-device-pixel-ratio: 1.5){
background:$bgcolor url($url) $x $y no-repeat;
background-size:$size;
}
@media only screen and (min-device-pixel-ratio: 1.5){
background:$bgcolor url($url) $x $y no-repeat;
background-size:$size;
}
@media only screen and (-o-min-device-pixel-ratio:3/2){
background:$bgcolor url($url) $x $y no-repeat;
background-size:$size;
}
}
@mixin ratioBackgroundPosition($x:0px ,$y:0px ){
@media only screen and (-webkit-min-device-pixel-ratio: 1.5){
background-position:$x $y;
}
@media only screen and (min--moz-device-pixel-ratio: 1.5){
background-position:$x $y;
}
@media only screen and (min-device-pixel-ratio: 1.5){
background-position:$x $y;
}
@media only screen and (-o-min-device-pixel-ratio:3/2){
background-position:$x $y;
}
}

然後在做項目時候,在scss文件中引用這個utils.scss文件,

具體使用方法如下

技術分享

我們這裏需要兩張雪碧圖,一張正常的一倍的,一張2倍圖。

這裏需要註意的是這裏面的參數

1.@include ratioBackground 是兼容Retina 屏幕需要引入的2倍那張圖,$size這個參數記得一定要寫成跟一倍圖一樣的大小。

2.@include ratioBackgroundPosition其實就是background-position,$x:0px ,$y:0px就很好理解了。

這樣就可以坐到兼容Retina 屏幕了。

這裏還要說一下兼容Retina 屏幕時雪碧圖要註意的問題。

雪碧圖對於前端來說並不陌生,它的好處我在這裏也不多說,想必大多數前端都知道。

我這裏要說的是基於上面的文件,我們怎麽做雪碧圖更簡單。

大家都知道一般兼容Retina 屏幕時候,都是一些小圖標,這時候我們做雪碧圖就非常重要了。

首先我們需要一套2倍的圖片。然後將2倍圖片變成雪碧圖,像這樣

技術分享

然後我們在ps中選擇圖像------圖像大小,然後將大小變成之前的二分之一,像這樣

技術分享

之後生成一個一倍圖片。

這樣做的好處是,我們在寫的時候,只需要改變引用的圖片,和$size,但background-position一倍圖和二倍圖是不需要改變的。這樣就節省了很多時間。

關於前端Retina 屏幕兼容和基於Retina 屏幕兼容的雪碧圖技巧