如何使用JavaScript在SVG中创建属性

How to create an attribute in SVG using JavaScript?

本文关键字:创建 属性 SVG 何使用 JavaScript      更新时间:2023-09-26

我的应用程序中有一个脚本,它在具有特定ID值的SVG中隐藏g元素,但这仅在g元素具有可视性属性时才有效。但是,我使用的svg在g元素上没有可见性属性,而且我无法控制源代码。因此,我需要找到一种在加载父HTML页面时动态添加visibility属性的方法。

我希望脚本在<g id="Callouts">的所有子元素上创建可见性属性。例如,最终代码看起来像这样:

<g id="Callouts">
  <g id="Callout1" visibility="visible">...</g>
  <g id="Callout2" visibility="visible">...</g>
</g>

我找遍了所有将属性添加到SVG结构的示例,但还没有找到任何东西。当涉及到JavaScript时,我是一个完全的新手,这也没有帮助。有人知道怎么做吗?

UPDATE:我将Digital Plane的建议代码与我用来访问SVG文档的代码结合在一起。结果函数如下所示。这应该表示<g id="Callouts">下的每一个g元素。但是,我总是在for循环中得到"object not supported"的错误。

function displayOnload (svgName) {
    var svgEmbed = document.embeds[svgName];
    if (typeof svgEmbed.getSVGDocument != 'undefined') {
        var svgDocument = svgEmbed.getSVGDocument();
        var parentElement = svgDocument.getElementById('Callouts');
        if (parentElement != null) {
            var childElements = parentElement.getElementsByTagname('g');
            for (var i=0; i < childElements.length; i++) {
                childElements[i].setAttribute('visibility', 'visible');
            }
        }
    }
}

请原谅我对JavaScript的无知,但我在这里做错了什么?

更新:这是我的HTML代码的一个例子。

<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:svg="http://www.w3.org/2000/svg">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>Drop Bar assembly (2328775)</title>
  <link rel="stylesheet" type="text/css" href="Content.css" />
  <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
  <script type="text/javascript">
    function displayOnload (svgName) {
      var svgEmbed = document.embeds[svgName];
      if (typeof svgEmbed.getSVGDocument != 'undefined') {
        var svgDocument = svgEmbed.getSVGDocument();
        var parentElement = svgDocument.getElementById('Callouts');
        var childElements = parentElement.getElementsByTagName('g');
        for (var i=0; i &lt; childElements.length; i++) {
          childElements[i].setAttribute('visibility', 'hidden');
        }
      }
     }
  </script>
  </head>
  <body onload="displayOnload('SVG')">
  ...
  </body>
</html>

您应该能够使用setAttribute,像这样:

element.setAttribute("visibility", "visible");

如果您希望所有g元素都是<g id="Callouts">的子元素,请在文档加载时执行此操作:

var element = document.getElementById("Callouts");
var elements = element.getElementsByTagName("g");
for(var i = 0; i < elements.length; i++)
  elements[i].setAttribute("visibility", "visible");

不能,必须使用setAttributeNS(null, 'visibility', 'visible);

setAttribute在某些浏览器上可能无法在/in svg上工作。

或者更直白地说:setAttribute为DOM1setAttributeNS为DOM2Svg有名称空间,Svg是xml所以setAttributeNS是为你的