G
G
Genri_Rus2019-09-24 01:21:00
JavaScript
Genri_Rus, 2019-09-24 01:21:00

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) { 
            
        }
});

Suppose there is a page If there is such a data-icon, then output svg to this element Any thoughts on how this can be implemented?
<div class="icon-m" data-icon="menu-icon"></div>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Kit, 2019-09-24
@ShadowOfCasper

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>
...

Well, instead of use, the markup of the symbol associated by id is substituted.
This way you can control the svg through both css and js. And all of them will lie in one sprite.
And of course, the process of compiling icons into a sprite - I use it through gulp.
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('&gt;', '>'))
      
      .on('error', function(err) {
        util.log(err);
      })
      .on('error', notify.onError('sprite compiling error!'))
      .pipe(gulp.dest(dest))
  });

path src and dest, as well as icon-by-icon processing through cheerio, you already customize for yourself

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question