尽管位于HTML源代码中,但DOM中的某些对象似乎没有呈现? [英] Certain Objects in DOM do not seem to render despite being in the HTML source?
问题描述
我是Web开发人员的新手,并且遇到了以下奇怪的问题.使用 d3.js
(特别是此脚本)时,我我们一直在尝试添加其他一些功能.我在javascript代码中添加了一个功能,该功能为DOM添加了一个简单的< p>
,当我在网站上呈现它并检查源代码时,我确实看到了它.这是相关HTML的子集:
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>
我添加了< p> hello</p>
标记,对我来说奇怪的是,每个其他元素都被渲染(绘制了一个圆圈,并且文本"2"是当前),但没有"hello"待观察.我尝试将 p
标记替换为 div
和 span
,但是除了使用实际的< text>
标记.通常,当我将鼠标悬停在浏览器(Chrome)中的HTML上时,该HTML表示的元素会突出显示,但是将鼠标悬停在< 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.
有人可以解释为什么会这样吗,请提供可能的解决方法?就上下文而言,我不仅对在此处添加文本感兴趣,而且还对添加文本感兴趣.我希望能够呈现一些更复杂的组件,这将需要能够将其他HTML元素类型呈现为 g
对象的子代.
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.
推荐答案
Hugo的回答也很好.出于我的目的,我发现添加 foreignobject
标签是最好的解决方案:
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>
一些注意事项:
- 这允许将元素嵌套在SVG元素中,这在不容易重构DOM元素的情况下可能会有所帮助.
- 由于某种原因(我不太清楚为什么),指定
foreignobject
的width
和height
属性很重要;否则,它可能无法渲染.
- 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.
这篇关于尽管位于HTML源代码中,但DOM中的某些对象似乎没有呈现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!