【问题标题】:Why I cannot reach the svg objects using from html object?为什么我无法使用来自 html 对象的 svg 对象?
【发布时间】:2022-06-11 00:19:20
【问题描述】:

网上的例子,他们可以很方便的调用svg文件中的对象。但我无法联系到他们。这是我的html代码``

<html lang="en">
<head>
<title>SVG Example</title>
    <script src="mysvg.js"></script>
</head>
<body>
    <div>
        <button style="width: 100px; height: 50px" onclick="changeColor()">Change Color</button>
        <object data="test.svg" type="image/svg+xml"></object>
    </div>
</body>
</html>

这是我的 .js 文件代码:

function changeColor() {
  const svg = document.getElementById("layer1");
  const motor1 = document.getElementById("g320");
  const ellipse = document.getElementById("ellipse205");
  ellipse.setAttribute("style","fill:green;stroke:green;stroke-width:2");
  motor1.appendChild(svg);
  ellipse.appendChild(motor1);
}

我做错了什么,为什么这不起作用?我不明白。

【问题讨论】:

  • 因为&lt;object&gt; 加载它类似于&lt;img&gt; 标签; SVG 确实 not 成为主 DOM 的一部分,因此您无法访问它。如果你不能内联 SVG,你 have to load it
  • @Danny'365CSI'Engelman 这是完全错误的。

标签: javascript html svg svg.js


【解决方案1】:

SVG &lt;object&gt; 的内容是与宿主文档不同的 DOM 的一部分。访问它是一个两步过程:

像这样:

document.querySelector('object[data="test.svg"]').addEventListener("load", function () {
    document.querySelector('button').addEventListener("click", changeColor);
}

function changeColor() {
    const innerDocument = this.contentDocument;
    const svg = innerDocument.getElementById("layer1");
    const motor1 = innerDocument.getElementById("g320");
    const ellipse = innerDocument.getElementById("ellipse205");
    ellipse.setAttribute("style","fill:green;stroke:green;stroke-width:2");
   motor1.appendChild(svg);
   ellipse.appendChild(motor1);

}

【讨论】:

    猜你喜欢
    • 2020-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    • 2018-11-19
    • 1970-01-01
    • 2011-11-18
    • 1970-01-01
    相关资源
    最近更新 更多