从JavaScript编辑SVG样式 [英] Editing SVG styles from javascript

查看:446
本文介绍了从JavaScript编辑SVG样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张SVG世界地图,并且我想通过更改svg中每个区域的样式属性,通过各种指标实时为每个区域着色.例如,我想将英国蓝色涂成浅色,以反映即将到来的保守党胜利.

由于数据经常更改并被推送到浏览器,因此它必须是动态的.

解决方案

您可以将CSS样式应用于SVG元素.不用说,这需要适当的标记.例如,如果您的地图看起来像(非常简化:-)

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

您可以简单地执行以下操作:

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

当然也可以将样式表嵌入到SVG文档中:

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

最后,还可以在SVG文档中包含外部样式表:

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

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.

解决方案

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

这篇关于从JavaScript编辑SVG样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆