如何在脚本中的特定位置添加文本?

时间:2022-11-23 14:05:16

How do I add a text in a specific location Dynamically? I can do:

如何动态添加特定位置的文本?我可以:

var txt = document.createTextNode("text")

But then I can't move it! I'm very sorry if this is a simple question but I'm Extremely new to JavaScript :-/

但后来我无法动弹!如果这是一个简单的问题,我很抱歉,但我对JavaScript非常陌生: - /

EDIT For example: What would you do if you had to add "This is a text" at the coordinates 450, 238 from inside the script?

编辑例如:如果你必须在脚本里面的坐标450,238处添加“这是一个文本”,你会怎么做?

1 个解决方案

#1


1  

It kind of depends on what your adding and where you are adding it. If you are adding text to an empty node for example then innerHtml is probably the easiest, fastest, and most performant way to do so. document.getElementById('container').innerHtml = 'text I want to insert'

这取决于您添加的内容以及添加内容的位置。例如,如果要向空节点添加文本,那么innerHtml可能是最简单,最快速,最高效的方式。 document.getElementById('container')。innerHtml ='text我要插入'

The caveat for this is that it will completely replace the contents of the container element with your text so you can't do this if you just want to add to the text.

需要注意的是,它将使用您的文本完全替换容器元素的内容,因此如果您只想添加到文本中,则无法执行此操作。

Otherwise as pst said in the comment on your questions calling document.getElementById('container').addChild(txtNode) will add a new child to the container node.

否则,正如pst在调用document.getElementById('container')的问题的评论中说的那样.addChild(txtNode)将向容器节点添加一个新子节点。

#1


1  

It kind of depends on what your adding and where you are adding it. If you are adding text to an empty node for example then innerHtml is probably the easiest, fastest, and most performant way to do so. document.getElementById('container').innerHtml = 'text I want to insert'

这取决于您添加的内容以及添加内容的位置。例如,如果要向空节点添加文本,那么innerHtml可能是最简单,最快速,最高效的方式。 document.getElementById('container')。innerHtml ='text我要插入'

The caveat for this is that it will completely replace the contents of the container element with your text so you can't do this if you just want to add to the text.

需要注意的是,它将使用您的文本完全替换容器元素的内容,因此如果您只想添加到文本中,则无法执行此操作。

Otherwise as pst said in the comment on your questions calling document.getElementById('container').addChild(txtNode) will add a new child to the container node.

否则,正如pst在调用document.getElementById('container')的问题的评论中说的那样.addChild(txtNode)将向容器节点添加一个新子节点。