[英]How to preserve whitespace in dynamically added javascript DOM element without using CSS?
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
。
White space characters are usually collapsed in HTML (by default) . 空格字符通常在HTML中折叠(默认情况下) 。
You can replace it with the
您可以将其替换为
entity: 实体:
var text = text.replace(/\s/g, ' ');
\\s
will match any white space character, such as space, tab and new line. \\s
将匹配任何空白字符,例如空格,制表符和新行。 If you only want to replace space, use / /g
instead. 如果您只想替换空格,请改用
/ /g
。
Other options which avoid string manipulation: 避免字符串操作的其他选项:
pre
element . pre
元素中 。 white-space
property to pre
as @Esailija pointed out. white-space
属性设置为pre
为@Esailija指出。 You can always add CSS properties dynamically to elements, they don't have to be specified in a style sheet. White space is collapsed in HTML. HTML中的空格已折叠。 It's not a JS issue, the same would happen if you typed that manually in the HTML document.
这不是JS问题,如果您在HTML文档中手动输入,也会发生同样的问题。 You need to replace the spaces with
您需要用&nbsp;替换空格
zlp.innerHTML = "hello hello".replace( / /g, " " );
use 采用
zlp.innerHTML = "hello hello";
Like everyone else just said. 就像其他人刚刚说的那样。
use a html tag 'pre' 使用html标签'pre'
Example: 例:
<pre>
A line
A line with indent
</pre>
result: 结果:
A line A line with indent
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.