Editing SVG styles from javascript

谁都会走 提交于 2020-07-08 05:51:27

问题


I have an SVG map of the world, and I want to colour each region by various metrics in real time by altering style attributes for each region in the svg. EG I want to tint the UK blue to reflect the upcoming tory victory (ahem).

This needs to be dynamic as the data changes often and is pushed out to the browser.


回答1:


You can apply CSS styling to SVG Elements. Needless to say, this requires a suitable markup. So for instance, if your map looks something like (VERY simplified :-)

<svg>
    <g id="USA">...</g>
    <g id="UK">...</g>
</svg>

You could simply do the following:

var country = document.getElementById("UK");
country.setAttribute("style", "fill: blue; stroke: black");

Of course it is also possible to embed stylesheets into an SVG document:

<svg>
  <defs>
    <style type="text/css">
      <![CDATA[
      // insert CSS rules here
      ]]>
    </style>
  </defs>
</svg>

And finally, it is also possible to include an external stylesheet into an SVG document:

<?xml version="1.0" standalone="no"?>
<?xml-stylesheet href="style.css" type="text/css"?>
<svg>
    ...



回答2:


I case you don't want to change the whole style, you can do:

var country = document.getElementById("UK");
country.style.fill = "blue";
country.style.stroke = "black";


来源:https://stackoverflow.com/questions/2463260/editing-svg-styles-from-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!