如何在不使用 CSS 的情况下在动态添加的 javascript DOM 元素中保留空格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10474696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:00:19  来源:igfitidea点击:

How to preserve whitespace in dynamically added javascript DOM element without using CSS?

javascriptdomdynamicwhitespace

提问by Travis J

When adding in text with small whitespace appended to it for alignment purposes the whitespace is trimmed off (the whitespace is added in c# so by the time it gets to front end Javascript it cannot be edited - it would be nice to just use some CSS to do this but it is not an option).

当添加带有小空格的文本以进行对齐时,空格会被修剪掉(空格是在 c# 中添加的,所以当它到达前端 Javascript 时,它无法被编辑 -只使用一些 CSS 会很好这样做,但它不是一个选项)。

Here is what I tried so far:

这是我到目前为止尝试过的:

<div id="testDiv"></div>
<script type="text/javascript">
 var zlp = document.getElementById("testDiv");
 zlp.innerHTML = "hello                hello";
 var zzz = document.createTextNode("hello                hello");
 zlp.appendChild(zzz);
</script>

Both of which produce hello hello.

两者都产生hello hello.

回答by Felix Kling

White space characters are usually collapsed in HTML (by default).

空白字符通常在 HTML 中折叠(默认情况下)

You can replace it with the &nbsp;entity:

您可以将其替换为&nbsp;实体:

var text = text.replace(/\s/g, '&nbsp;');

\swill match any white space character, such as space, tab and new line. If you only want to replace space, use / /ginstead.

\s将匹配任何空白字符,例如空格、制表符和换行符。如果您只想替换空间,请/ /g改用。

Other options which avoid string manipulation:

避免字符串操作的其他选项:

  • Put the text in a preelement.
  • Set the CSS 2 white-spaceproperty to preas @Esailijapointed out. You can always add CSS properties dynamically to elements, they don't have to be specified in a style sheet.
  • 将文本放入pre元素中
  • 将 CSS 2white-space属性设置pre@Esalija指出的那样。你总是可以动态地向元素添加 CSS 属性,它们不必在样式表中指定。

回答by gotofritz

White space is collapsed in HTML. It's not a JS issue, the same would happen if you typed that manually in the HTML document. You need to replace the spaces with &nbsp;

空白在 HTML 中折叠。这不是 JS 问题,如果您在 HTML 文档中手动输入,也会发生同样的情况。您需要用   替换空格

zlp.innerHTML = "hello                hello".replace( / /g, "&nbsp;" );

回答by PitaJ

use  

利用  

zlp.innerHTML = "hello&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;hello";

Like everyone else just said.

就像其他人刚刚说的那样。

回答by Wagner Pereira

use a html tag 'pre'

使用 html 标签“pre”

Example:

例子:

<pre>
A line
   A line with indent
</pre>

result:

结果:

A line
   A line with indent