【问题标题】:Safari fails to replace SVG element with: NoModificationAllowedError: The object can not be modifiedSafari 无法将 SVG 元素替换为:NoModificationAllowedError:无法修改对象
【发布时间】:2021-06-16 21:56:44
【问题描述】:

我想用 foreignObject 替换我所有 SVG 的 <rect> 元素,这在 FireFox 和基于 Chromium 的浏览器中运行良好,但在 Safari 中失败。

MWE:

HTML/SVG

<!DOCTYPE html>
<html lang="en">
  <body>
    <svg>
      <rect id="rect1" width="100" height="100" />
    </svg>
  </body>
</html>

JavaScript

let myRect = document.getElementById("rect1")
myRect.outerHTML = myRect.outerHTML.replace("<rect", "<foreignObject").replace("</rect>", "</foreignObject>")

Safari 失败并显示:NoModificationAllowedError: The object can not be modified.

我知道问题是由于outerHTML 位于 HTML 命名空间上,而 SVG 位于 XML 上,但有没有办法在 SVG 中实现这一点?

感谢您对此问题的任何见解。

【问题讨论】:

    标签: javascript html svg safari foreignobject


    【解决方案1】:

    替换字符串很容易出错

    替换元素..复制属性

    <svg id=SVG>
      <rect id="rect1" width="100" height="100" />
      <g>    
        <rect id="rect2" width="100" height="100" />
      </g>
    </svg>
    
    <script>
      let svg = SVG;
      svg.querySelectorAll("rect").forEach(rect => {
        let obj = document.createElementNS("http://www.w3.org/2000/svg", "foreignObject");
        [...rect.attributes].map(  ({name,value}) => obj.setAttribute(name, value)  );
        rect.replaceWith(obj);
      });
      console.log(SVG.outerHTML);
    </script>

    对于 IE11,PS 无法读取 rect.parentNode.replaceChild(obj, rect);

    【讨论】:

    • 太棒了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多