SVG颜色填充不适用于JavaScript

时间:2018-08-28 19:45:16

标签: javascript html svg

我正在使用SVG和Javascript制作地图。我的问题是,当我使用fill时,什么都没有改变。

map.svg

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 214.5 156" style="enable-background:new 0 0 214.5 156;" xml:space="preserve">

    <style type="text/css">
        .st0{fill:#ffffff;stroke:#000000;}
    </style>

    <g id="province1"> <!-- I want to fill this with color -->
        <path id="XMLID_84_" class="st0" d="M106.8,120.9l-0.1-0.6l-0.2-0.9l 0.6- 1.7l0,0l-0.5-0.2l-3.4-1.2l-1.2-1.7l0.5,0l0.6,0l0.2,0 l0.1,0l0.1-0.1l1-0.9l1-1.6l0 0.1l0,0l0.1,0l0.1,0l0.7,0.1l2.8,0.6l0,0l0.1,0.2l0.1,0.3l0.1,0.2l0.1,0.1l0.1,0.1 2.6,0l0.4,0 l1.2-0.1l0.2-0.1l2.1-1.8l0.1-0.2l0-0.4l0-0.1l0,0l-0.8-0.5l-0.2-0.1l0.4-1.1l1.3-1.6l0.1,0l0.1,0.1l0.1,0.2l0.4,0.6l0.2,0.5 l0.7,0.6l2.1,0.5l1.6,0l0.2,0l0.2-0.1l0.1,0.2l0.1,0l1.3,0.7l0.6,0.2l1.3,0.4l1.1,0l0.1,0l0.1,0l0.2,0l1.5,1.3l0.3,0.4l-0.9,1.9 l1,1.5l-1.1,0.6l-0.8,0.5l-0.5,0.5l-2.5,1.4l-0.6,0.2l-0.4,0.1l-0.4,0l-1-0.6l-0.6,0l-3.8,1.6l-0.1,0.1L116,121l-0.5,0.3l-0.1,0.1 l-0.8,1.3l-0.2,0.3l0.1,0.3l-0.3,0.2l-0.5,0.2l-0.2,0l-2.8,0.2l-0.9-0.1l-0.3,0l-0.1-0.1l0,0l0-0.1l-0.1-1.1l0-0.6l-2.6-0.8 L106.8,120.9z"/>
    </g>

    <!-- other provinces here, a lot of them -->

</svg>

index.html

<div class="map">
    <object class="map-1" id="map" data="map.svg" type="image/svg+xml" height="100%" width="100%">
    </object>
</div>

main.js

window.onload=function() {
    document.getElementById("map").getSVGDocument().getElementById("province1").setAttribute("fill", "#f94d4d");
};

1 个答案:

答案 0 :(得分:1)

正如罗伯特所说,st0类将覆盖您要添加到父组的fill属性。

您需要执行以下操作:

window.onload=function() {
  var doc = document.getElementById("map").getSVGDocument();
  doc.getElementById("province1").setAttribute("fill", "#f94d4d");
  doc.getElementById("XMLID_84_").removeAttribute("class");
};