简体   繁体   中英

How can I access from CSS to the elements within the SVG file?

  • I have a svg file. I'm adding it through the <object data = "img/img.svg" type = "image/svg + xml">...
  • Svg file contains tag "path" with attribute "fill" .
  • This svg file needs to be used several times, and use a different color for "fill" . it is necessary something like div.red #pathId {fill: red} and div.green #pathId {fill: green}
  • Css property do not apply to this svg file, as on the page it is similar to the iframe way, and => css not apply.
  • I know that we can in SVG file to specify the path to the CSS file. But then all the styles of this CSS file is used only for the SVG file. ( .red and .green not available in SVG and => it does not apply)

Is there any solution without using JS? (With JS we can get the contents of SVG through .contentDocument and set the fill attribute)

You can only access to the SVG if the SVG is an element of the HTML-DOM like this:

<div class="svg">
  <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="566.93px" height="1133.858px" viewBox="0 0 566.93 1133.858" enable-background="new 0 0 566.93 1133.858" xml:space="preserve">...</svg>
</div>

It's a html snippet from one of my projects. In the global css there are basic some styles:

.svg {
  height: 400px;
  width: 400px;
}

svg {
  height: 100%;
  width: 100%;
}

To include the SVG I use the following mechanism:

HTML:

<div class="svg" data-svgpath="img/img.svg"></div>

JS:

function loadSvg(container) {
    if (container.dataset.svgpath) {
        $(container).load(container.dataset.svgpath, function(resp, status, xhr) {
            container.classList.add('is-loaded');
        });
    }
}

Load SVG and inject into the DOM:

$('.svg').each(function() {
    loadSvg(this);
});

This is a short summary of what I do in the project and it works like a charm. I have access through the global css and js, because I manipulate the visibility of groups in the SVG too.

The browser support of inline svg is quite well: http://caniuse.com/#feat=svg-html5

EDIT: Ah my mistake: you are looking for a solution without JS. Hm, sorry but may it's still helpful for you or someone other.

Ciao Ralf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM