移動端開發中,使用gulp.spritesmith進行小圖sprite並生成樣式,但由於spritesmith默認是以px為單位,所以就把插件的內容修改了下讓生成rem單位並且能把background-size設置為雪碧圖的寬高。
1.首先修改gulp.spritesmith\node_modules\spritesheet-templates\lib\spritesheet-templates.js
['x', 'y', 'offset_x', 'offset_y', 'height', 'width', 'total_height', 'total_width'].forEach(function (key) { if (item[key] !== undefined) { px[key] = item[key]/64 + 'rem'; } });
修改的地方是item[key]/64+'rem';這句,我的是設置了640px寬度,所以這里除以64來轉換得到rem值。
2.修改gulp.spritesmith\node_modules\spritesheet-templates\lib\templates\css.template.handlebars
在模板頁中加入生成background-size內容
{{/block}} {{#block "sprites"}} .cicon { display: inline-block; background-size: {{spritesheet.px.width}} {{spritesheet.px.height}}; } {{#each sprites}} {{{selector}}} { background-image: url({{{escaped_image}}}); background-position: {{px.offset_x}} {{px.offset_y}}; width: {{px.width}}; height: {{px.height}}; } {{/each}} {{/block}}
主要添加了加粗的代碼行。以上兩點修改完成就可以把spritesmith生成的px轉換成rem,增加background-size主要是因為px單位下圖片背景位置跟大小默認就是雪碧圖中的大小,所以轉換成rem后需要進行修改。
PS:rem單位下在不同設備中可能出現圖片中出現了雪碧圖中其他圖的邊邊角角,所以這里需要設置圖片合成的時候彼此之間有一定的間隙,這個只要是gulpfile中設置下padding:10即可。
var spriteData = gulp.src(base_url+'_images/icons/*.+(jpeg|jpg|png)').pipe(spritesmith({ imgName: 'icons_sprite.png', cssName: 'icons_sprite.css', cssFormat: 'css', padding: 10 }));