Answer the question
In order to leave comments, you need to log in
How to display an svg sprite depending on the data element on the page?
Here is an example:
$(function() {
var icon = [
{'menu-icon' : "<svg viewBox=\"0 0 42 42\">\
<circle cx=\"20\" cy=\"20\" r=\"19\" stroke=\"white\" stroke-width=\"2\"/>\
<g class=\"change-color\">\
<circle cx=\"19.5\" cy=\"10.5\" r=\"2.5\" fill=\"currentColor\"/>\
<circle cx=\"19.5\" cy=\"19.5\" r=\"2.5\" fill=\"currentColor\"/>\
<circle cx=\"19.5\" cy=\"28.5\" r=\"2.5\" fill=\"currentColor\"/>\
</g>\
<\/svg>"}
]
for (let i in icon) {
}
});
<div class="icon-m" data-icon="menu-icon"></div>
Answer the question
In order to leave comments, you need to log in
So character sprite is your case
In html code would be:
The sprite code needs characters that are substituted by id.
Here is an example of a piece of sprite, just so you understand how it works
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><symbol fill="none" viewBox="0 0 18 18" id="archive" xmlns="http://www.w3.org/2000/svg"><path d="M9 0v10.42m0 0L6.143 7.676M9 10.42l2.857-2.742M6 5H4.5L1 12m0 0v5h16v-5M1 12h4a1 1 0 011 1 1 1 0 001 1h4a1 1 0 001-1 1 1 0 011-1h4m0 0l-3.5-7H12"/></symbol>
...
const gulp = require('gulp'),
cheerio = require('gulp-cheerio'),
svgmin = require('gulp-svgmin'),
replace = require('gulp-replace'),
util = require('gulp-util'),
notify = require('gulp-notify'),
svgSprite = require('gulp-svg-sprite'),
path = require('path');
let dest = path.join('src', 'assets', 'icons');
let svgConfig = {
mode: {
symbol:{
sprite: "../sprite.svg"
}
}
};
gulp.task('sprite', function() {
gulp.src("**/*.svg", {cwd: path.join(dest, 'exported')})
.pipe(svgSprite(svgConfig))
.pipe(cheerio({
run: function ($) {
$('[stroke]').removeAttr('stroke');
$('[viewBox]').attr('viewBox', '0 0 18 18');
return
},
parserOptions: {xmlMode: true}
}))
.pipe(replace('>', '>'))
.on('error', function(err) {
util.log(err);
})
.on('error', notify.onError('sprite compiling error!'))
.pipe(gulp.dest(dest))
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question