在 SVG 文件中包含外部 JS 脚本不起作用

时间:2021-05-30 20:11:38

标签: javascript html svg href external


我目前正在做一个项目,我想在其中包含一个外部 SVG 文件到我的 html 站点。外部 JS 文件应该操作 svg 中单个元素的颜色。但有些东西不起作用。
  • 我将 svg 文件作为对象包含在我的 html 文件中。像这样:
<object id="simulationObject" data="../svg/RS_Simulation.svg" type="image/svg+xml" width="780" height="420">Your browser doesn't support SVGs</object>
  • 我的 SVG 文件有以下开头:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml-stylesheet href="../css/stylesheet.css" type="text/css"?>
<?xml-stylesheet href="../css/RS_Flipflop_style.css" type="text/css"?>
<svg id="simulationSVG" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" sodipodi:docname="RS_Simulation.svg ">
  • 在我插入的 svg 文件的底部:
<script type="text/JavaScript" xlink:href="../javascript/RS_Flipflop.js" />

</svg>
  • 最后但并非最不重要的是,我的 JS 文件如下所示:
onload = (event) => {
    document.getElementsByClassName('gateDown').style.stroke = 'black';
}

在我的 JS 文件中,我尝试了多种方法,例如使用 setAttribute(...) 或 setAttributeNS(...)。没有一个工作。我究竟做错了什么?是不是有什么小问题,可以轻松解决还是整个概念是错误的?

顺便说一句: 如果我只是将 svg 放在我的 html 文件中,我完全没有问题。所以不像我那样在一个额外的文件中。但是,只有在以其他方式无法实现的情况下,这才是可行的方法。原因是,我的 SVG 文件很长(是的,我写了它们。Inkscape 中没有很多东西)。我还需要在多个 html 文件中使用相同的 SVG。将代码直接包含在 svg 标签中的这些文件中会很痛苦。

0 个答案:

没有答案