【问题标题】:Get and remove <defs> elements from <svg> with javascript使用 javascript 从 <svg> 中获取和删除 <defs> 元素
【发布时间】:2021-05-24 12:51:38
【问题描述】:

有没有办法使用纯 javascript 或 jquery 从 &lt;svg&gt; 中删除 &lt;defs&gt; 元素?

我找到了 d3 库的解决方案,但我想避免为此添加整个库。

【问题讨论】:

标签: javascript jquery svg


【解决方案1】:

使用ChildNode.remove() 删除元素并将所需的选择器传递给querySelector

document.querySelector("defs").remove();
<svg viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink">
  <!-- Some graphical objects to use -->
  <defs>
    <circle id="myCircle" cx="0" cy="0" r="5" />

    <linearGradient id="myGradient" gradientTransform="rotate(90)">
      <stop offset="20%" stop-color="gold" />
      <stop offset="90%" stop-color="red" />
    </linearGradient>
  </defs>

  <!-- using my graphical objects -->
  <use x="5" y="5" xlink:href="#myCircle" fill="url('#myGradient')" />
</svg>

对于多个元素,使用 querySelectorAll 和 NodeList.forEach:

document.querySelectorAll("defs").forEach(EL => EL.remove());

【讨论】:

    猜你喜欢
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 2019-06-27
    • 2012-04-15
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    • 2016-10-04
    相关资源
    最近更新 更多