Styling the same SVG <object> different ways

前端 未结 4 1275
抹茶落季
抹茶落季 2021-01-05 06:05

I want to have a series of the same SVG file on a page with different colours. I\'m aware that the best method of getting the SVG into the page without bloating the code, an

4条回答
  •  隐瞒了意图╮
    2021-01-05 06:45

    I was in the same predicament, but realized it's simply not possible per the current spec because SVG documents exist in their own DOM separate from the main document, similar to iframes (see this answer). However, that doesn't mean we can't hack our way around this limitation for the time being.

    Since SVG files are plain text files, I figured why not just render it using JavaScript (being that the question did not explicitly state that JS cannot be used). Using the SVG circle above as an example, the function would look like this:

    // Render an SVG circle
    // optional oStyles = { selector: style [, ...] }
    function renderCircle(oStyles) {
      var sId = ('svg-'+performance.now()).replace('.', ''),
        sCss = '',
        sSel;
      if (!oStyles) oStyles = {};
      for (var i in oStyles) {
        // Handle group of selectors
        sSel = '';
        i.split(/ *, */).forEach(function(s) {
          sSel += '#' + sId + ' ' + s + ',';
        });
        sSel = sSel.slice(0, -1);
        sCss += sSel + '{' + oStyles[i] + '}';
      }
      return '' +
        '' +
          '' +
          '' +
        '';
    }
    
    document.getElementById('canvas').innerHTML = renderCircle();
    document.getElementById('canvas').innerHTML += renderCircle({'.svg-circle':'fill:blue'});

    This works okay for a one-off image like a logo, but if you have a bunch of SVG icons, then you should consider using an SVG icon font or SVG sprites. Here's a good guide for implementing SVGs for the web in general:

    https://svgontheweb.com/

提交回复
热议问题