问题
I'm quite new to web dev, and I've encountered the following odd issue. While using d3.js
(specifically this script), I've been trying to add some other features. I've added a feature in my javascript code that adds a simple <p>
to the DOM, and when I render it on my website and inspect source, I see it is indeed there. Here is a subset of the relevant HTML:
<g class="node" transform="translate(180, 37.5)" style="stroke: rgb(128, 128, 128);">
<circle class="node" r="10" id="node_2" cursor="pointer" style="fill: lightsteelblue;"></circle>
<text dy=".35em" x="-13" text-anchor="end">2</text></g>
<p>hello</p>
I added the <p>hello</p>
tag, and what's strange to me is that every other element is rendered (a circle is drawn, and the text "2" is present) but there is no "hello" to be seen. I tried replacing the p
tag with div
and span
, but none will render the text except using the actual <text>
tag. Usually, when I hover over HTML in my Browser (Chrome), the element represented by that HTML is highlighted, but hovering over the <p>
tag yields nothing.
Could someone explain why this is, and offer a potential fix please? For context, I'm not just interested in adding text here; I want to be able to render some more complicated components, which will require being able to render other HTML element types as children of the g
object.
回答1:
Another solution could be to overlay your HTML children on top of the SVG with position: absolute:
<div class="container">
<svg></svg>
<p id="text">hello</p>
</div>
CSS:
.container {
position: relative;
}
.container #text {
position: absolute;
left: 50%;
top: 50%;
}
回答2:
Hugo's answer is also good. For my purposes, I found the addition of the foreignobject
tag was the best solution:
<g class="node" transform="translate(180, 37.5)" style="stroke: rgb(128, 128, 128);">
<circle class="node" r="10" id="node_2" cursor="pointer" style="fill: lightsteelblue;"></circle>
<text dy=".35em" x="-13" text-anchor="end">2</text></g>
<foreignobject width="100" height = "100">
<p>hello</p>
</foreignobject>
A couple notes:
- This allows for nesting of elements in the SVG element, which may be helpful when it's not easy to restructure the DOM elements.
- For some reason (I'm not completely sure why), it's important to specify the
width
andheight
attribute of theforeignobject
; otherwise, it might not render.
来源:https://stackoverflow.com/questions/63417264/certain-objects-in-dom-do-not-seem-to-render-despite-being-in-the-html-source