search
HomeWeb Front-endHTML Tutorial使用grunt对css中的background图片自动生成雪碧图_html/css_WEB-ITnose

公司研发的系统为B/S架构,用户使用浏览器访问系统时,使用浏览器自带工具查看,对图片的请求数极多,多为小图片。

今天想对这个现状进行改善,网上查到一种雪碧图的方案,其实就是使用工具将数量很多的小图片拼成一张大图片,然后css里都引用这张大图片,并指定显示该图片的某一个区域,但这个方案需要手工作很多处理。

于是就想到能不能用目前比较成熟的grunt对前端样式文件自动进行处理,自动生成雪碧图,自动修改样式文件。一搜索果然找到了方案,下面为Gruntfile.js文件的片断:

module.exports = function(grunt) {  // Project configuration.  grunt.initConfig({    // 自动雪碧图    sprite: {      options: {        // 映射CSS中背景路径,支持函数和数组,默认为 null        imagepath_map: null,        // 各图片间间距,如果设置为奇数,会强制+1以保证生成的2x图片为偶数宽高,默认 0        padding: 0,        // 是否使用 image-set 作为2x图片实现,默认不使用        useimageset: false,        // 是否以时间戳为文件名生成新的雪碧图文件,如果启用请注意清理之前生成的文件,默认不生成新文件        newsprite: false,        // 给雪碧图追加时间戳,默认不追加        spritestamp: true,        // 在CSS文件末尾追加时间戳,默认不追加        cssstamp: true,        // 默认使用二叉树最优排列算法        algorithm: 'binary-tree',        // 默认使用`pixelsmith`图像处理引擎        engine: 'pixelsmith'      },      sprite_module1: { //只对module1目录进行自动生成雪碧图处理        options : {          // sprite背景图源文件夹,只有匹配此路径才会处理,默认 images/slice/          imagepath: 'module1/images/',          // 雪碧图输出目录,注意,会覆盖之前文件!默认 images/          spritedest: 'module1/images/'        },        files: [{          // 启用动态扩展          expand: true,          // css文件源的文件夹          cwd: 'module1/',          // 匹配规则          src: ['**/*.css', '!**/*.sprite.css'],          // 导出css和sprite的路径地址          dest: 'module1/',          // 导出的css名          ext: '.sprite.css',          extDot: 'last'        }]      }    }  });    // 加载包含 "sprite" 任务的插件。  // grunt.loadNpmTasks('grunt-css-sprite'); //因为希望生成的雪碧图为.sprite.png结尾,对原来的grunt-css-sprite作了些改动,于是手动加载grunt_tasks  grunt.loadTasks('grunt_tasks');  grunt.registerTask('default', ['sprite']);};

package.json:

{  "name": "xxx",  "version": "x.x.x",  "devDependencies": {    "grunt": "0.4.5",    "async": "0.9.0",    "spritesmith": "1.3.0"  }}

grunt_tasks目录结构如下:

其中

sprite.js 从 https://github.com/laoshu133/grunt-css-sprite 工程里得来

css-spritesmith.js、imageSetSpriteCreator.js、place_after.png、place_before.png 从 https://github.com/laoshu133/css-spritesmith 工程里得来,但修改了css-spritesmith.js文件

...sliceData.timestamp = options.spritestamp ? timeNow : '';sliceData.timestamp = options.spritestamp ? ('?'+timeNow) : '';sliceData.imgDest = fixPath(path.join(options.spritedest, cssFilename + '.sprite.png'));sliceData.spriteImg = fixPath(path.join(options.spritepath, cssFilename + '.sprite.png')) +    sliceData.timestamp;sliceData.retinaImgDest = fixPath(sliceData.imgDest.replace(/\.png$/, '@2x.sprite.png'));sliceData.retinaSpriteImg = fixPath(path.join(options.spritepath, cssFilename + '@2x.sprite.png')) +  sliceData.timestamp;...


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Future of HTML, CSS, and JavaScript: Web Development TrendsThe Future of HTML, CSS, and JavaScript: Web Development TrendsApr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

HTML: The Structure, CSS: The Style, JavaScript: The BehaviorHTML: The Structure, CSS: The Style, JavaScript: The BehaviorApr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML: Evolution and Trends in Web DesignThe Future of HTML: Evolution and Trends in Web DesignApr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

Understanding HTML, CSS, and JavaScript: A Beginner's GuideUnderstanding HTML, CSS, and JavaScript: A Beginner's GuideApr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor