在SVG中添加带有子元素的元素,但未显示

时间:2018-06-26 13:22:45

标签: javascript html dom svg mermaid

我正在使用mermaid.js库生成序列图。

生成的序列图将忽略“角色”(矩形中的文本)长度。我想裁剪文本,美人鱼不支持。

使用foreignObject svg元素,可以指定尺寸。这就是为什么我决定将元素添加到foreignObject中以将其裁剪为foreignObject维度的原因。

这种方法的问题是,在将文本放到foreignObject中并且不再显示foreignObject本身之后,不再显示该文本。 我已经用d3尝试了类似的方法,但是结果相同。

这是我的代码:(正在运行的JSFiddle:https://jsfiddle.net/gLxkyz0j/2/

<!DOCTYPE html>
<meta charset="utf-8">
<body>

    <div class="mermaidParent">
        <div class="mermaid" id="svgParent">
            sequenceDiagram
            participant A as BLABLABALAIUHDZIUZAHDAIUHZDIAZ
            participant B as BLABLABALAIUHDZIUZAHDAIUHZDIAZ | FacadeDao
            A->>B: getSomeBlabla V1:0 (colocated)
            B-->>A: F1844 (16 ms)
        </div>
    </div>
<script src="https://unpkg.com/d3@5.5.0/dist/d3.js"></script>
<script src="https://unpkg.com/mermaid@8.0.0-rc.8/dist/mermaid.js"></script>

<script>
    mermaid.initialize(
        {
            startOnLoad: true,
            sequence: {
                useMaxWidth: true,
                htmlLabels: false,
                useMaxWidth: true,
                width: 200
            },
        }   
    );
</script>
<script>

    setTimeout(function() {

        const actorRects = document.querySelectorAll('g > rect');
        (function() {
        actorRects.forEach(rect => {
            const parent = rect.parentNode;

            let textContainer = document.createElement("foreignObject");
            textContainer.setAttribute("x", "0");
            textContainer.setAttribute("y", "0");
            textContainer.setAttribute("width","200");
            textContainer.setAttribute("height", "200");

            textContainer.appendChild(parent.querySelector('text'));   
            parent.appendChild(textContainer);

        });
        })();    
    }, 200);

</script>
</body>
</html>

但是有趣的是,当我正确显示重新渲染的文本后,当我使用Firefox上的Developper工具栏并“编辑为html” foreignObject或childNode时。

我完全不知道为什么它不起作用,非常感谢。

0 个答案:

没有答案
相关问题