如何使用JS触发SVG渲染,就像在Chrome中手动编辑DOM一样?

问题描述 投票:0回答:1

当我在 Chrome 中通过 JS 修改 HTML 文档中的 SVG 元素的 DOM 结构时(特别是使用 ReplaceWith 或appendChild 引入新内容),尽管 Chrome Elements 树反映了修改,但结果是 not 渲染的。 但是,如果我通过在违规修改上方编辑为 HTML 对 DOM 内容进行any手动编辑,这将导致 DOM 中后代的任何未渲染内容被渲染。 向任何祖先元素添加一个空格就可以了。 Chrome 中的编辑显然会触发某种更深层次的重新渲染,这就是我想以编程方式访问的内容。

JS 有办法做到这一点吗? 请注意,我确实测试了明显的“使用 JS 修改 DOM”,但这并不具有手动执行的效果。

document.body.insertAdjacentText('afterbegin', 'XXXX')

我提供给 ReplaceWith 的节点来自 HTML 中的一个部分,如下所示:

<template id=mytemplate>
<rect width="139.12148" height="130.4722" x="298.91934" y="233.69247"></rect>
</template>

这是我的 JS:

clone = document.querySelector('#mytemplate').content.cloneNode(true).firstChild;
placeholder = document.querySelector('#placeholderelementinSVG');
placeholder.replaceWith(clone);
javascript html svg dom
1个回答
0
投票

你有两个问题。

  1. 这不是一个 SVG 矩形,而是一个 HTML 矩形。 SVG 矩形需要在 HTML 中具有祖先
    <svg>
    元素。
  2. firstChild 将为您提供
    <template>
    元素末尾和
    <rect>
    元素开头之间的空白。

我已经纠正了下面的两个问题。考虑到矩形的位置,您可能需要将片段制作为整页才能看到矩形。

let clone = document.querySelector('#mytemplate').content.children[0].children[0].cloneNode(true);
placeholder = document.querySelector('#placeholderelementinSVG');
placeholder.replaceWith(clone);
html, body {
  width: 100%;
  height: 100%;
}
<template id=mytemplate>
<svg>
<rect width="139.12148" height="130.4722" x="298.91934" y="233.69247"></rect>
</svg>
</template>
<svg width="100%" height="100%"><rect id="placeholderelementinSVG"/></svg>

© www.soinside.com 2019 - 2024. All rights reserved.