javascript - 从外部文件将 svg 路径加载到 DOM 中

标签 javascript css svg dom

我想知道是否有一种方法可以从外部加载 svg 并且能够访问任何路径元素?到目前为止,当我加载外部 SVG 文件时,它会显示出来,但我无法访问任何特定路径。有没有方法/函数可以完成此任务?

例如,如果 SVG 仅位于 index.html 文件中,我可以使用 CSS 更改六边形的颜色。如果 SVG 很小,这不是问题,但对于更复杂的 SVG,为了清晰起见,我想将它们保存在单独的文件中。

#hexagon1 {
  opacity: 1;
  fill: #ffb619;
  stroke-width: 4.50001;
  stroke-linecap: round;
  stroke-miterlimit: 7
}

#hexagon2 {
  opacity: 1;
  fill: #008000;
  stroke-width: 4.50001;
  stroke-linecap: round;
  stroke-miterlimit: 7
}
<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" width="101.83981mm" height="74.999893mm"
  viewBox="0 0 101.83981 74.999893" version="1.1" id="svg8">
  <defs
     id="defs2" />
  <metadata
     id="metadata5">
    <rdf:RDF>
      <cc:Work
         rdf:about="">
        <dc:format>image/svg+xml</dc:format>
        <dc:type
           rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
        <dc:title></dc:title>
      </cc:Work>
    </rdf:RDF>
  </metadata>
  <g
     id="layer1"
     transform="translate(-28.970265,-13.579265)">
    <path
       id="hexagon1"
       d="M 43.906288,64.275181 28.970265,39.449215 43.002172,14.101257 71.9701,13.579265 86.906123,38.405231 72.874217,63.753189 Z" />
    <path
       id="hexagon2"
       d="M 87.810242,88.579156 72.874219,63.753189 86.906125,38.405231 115.87405,37.883239 130.81008,62.709205 116.77817,88.057164 Z" />
  </g>
</svg>

最佳答案

尝试 <object> tagdata=image/svg+xml .

<object type="image/svg+xml" data="https://upload.wikimedia.org/wikipedia/commons/8/8c/SVG_logo_h.svg"></object>

用于访问 <object> 的内容文档引用this answer 。简而言之:

const COLORS = ['red', 'orange', 'gold', 'forestgreen', 'blue', 'purple'];
const svg = document.querySelector('.svg-logo');

svg.addEventListener('load', () => {
  const svgDoc = svg.contentDocument;
  const hex1 = svgDoc.getElementById("hexagon1");
  const hex2 = svgDoc.getElementById("hexagon2");

  let i = 0;
  window.setInterval(() => {
    const j = i + 2 % COLORS.length;

    hex1.fill = COLORS[i];
    hex2.fill = COLORS[j];

    i = i + 1 % COLORS.length;
  }, 500)
});

关于javascript - 从外部文件将 svg 路径加载到 DOM 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65785734/

相关文章:

javascript - 嵌套列表权重和算法问题

html - 将鼠标悬停在 <li> 上使其他 <ul> 消失

javascript - 如何保持响应式移动菜单处于事件状态?

javascript - 单击时更改 SVG 填充覆盖 - jQuery

javascript - 使用 antd 自定义 svg 图标,如何将 Prop 传递给 svg?

javascript - 为什么 svg animateTransform 只在第一项上激活?

javascript - 在javascript中选择两个没有id的iframe之一

javascript - 使用 AngularJS 将 date() 保存在 JSON 中

javascript - 设置 css 元素的背景图像

html - 单个 svg 文件