我用的是在线的工具CSS Sprite Generator
css--所有需要自适应图片的部分加上sprite类
.sprite {
background-image: url(../image/icon_sprite.png);
background-repeat: no-repeat;
background-size: 100%;
}
js--setting需要自适应的元素的css属性
//sprite setting
$('.sprite-title').attr('widthHeight','{w:640,h:63}');
$('.sprite-title').attr('bgPosition','{l:-5,t:-185}');
$('.sprite-add').attr('widthHeight','{w:61,h:53}');
$('.sprite-add').attr('bgPosition','{l:-5,t:-5}');
$('.sprite-add').attr('fixedHeight','30');
$('.sprite-dec').attr('widthHeight','{w:61,h:53}');
$('.sprite-dec').attr('bgPosition','{l:-418,t:-5}');
$('.sprite-dec').attr('fixedHeight','30');//定高
$('.sprite-drop3').attr('widthHeight','{w:46,h:46}');
$('.sprite-drop3').attr('bgPosition','{l:-489,t:-5}');
$('.drop2').attr('fixedWidth','25');
$('.sprite-drop4').attr('widthHeight','{w:46,h:46}');
$('.sprite-drop4').attr('bgPosition','{l:-545,t:-5}');
$('.drop1').attr('fixedWidth','25');//定宽
$('.sprite-g1').attr('widthHeight','{w:60,h:60}');
$('.sprite-g1').attr('bgPosition','{l:-489,t:-61}');
$('.sprite-g1').attr('fixedWidth','25');
$('.sprite-g2').attr('widthHeight','{w:60,h:60}');
$('.sprite-g2').attr('bgPosition','{l:-559,t:-61}');
$('.sprite-g2').attr('fixedWidth','25');
$('.sprite-g33').attr('widthHeight','{w:60,h:60}');
$('.sprite-g33').attr('bgPosition','{l:-5,t:-123}');
$('.sprite-g33').attr('fixedWidth','25');
最终处理方法 写在$(function(){})中,如下:
var clientWidth=document.documentElement.clientWidth;
$('.sprite').each(function(){
var rate=clientWidth/640;
var widthHeight=$(this).attr('widthHeight');
var bgPosition=$(this).attr('bgPosition');
widthHeight=eval('('+widthHeight+')');
bgPosition=eval('('+bgPosition+')');
if($(this).attr('fixedHeight')){
var fixedHeight=parseInt($(this).attr('fixedHeight'));
rate=fixedHeight/widthHeight.h;
}else if($(this).attr('fixedWidth')){
var fixedWidth=parseInt($(this).attr('fixedWidth'));
rate=fixedWidth/widthHeight.w;
}else if($(this).hasClass('sprite-checkbox')){
return;
}
$(this).css('width',(widthHeight.w*rate)+'px');
$(this).css('height',(widthHeight.h*rate)+'px');
$(this).css('background-position',(bgPosition.l*rate)+'px '+(bgPosition.t*rate)+'px');
$(this).css('background-size',650*rate+'px');
});