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

ぐ巨炮叔叔 提交于 2020-01-10 05:10:45

问题


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).

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.


回答1:


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

You can replace it with the &nbsp; entity:

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

\s will match any white space character, such as space, tab and new line. If you only want to replace space, use / /g instead.

Other options which avoid string manipulation:

  • Put the text in a pre element.
  • Set the CSS 2 white-space property to pre as @Esailija pointed out. You can always add CSS properties dynamically to elements, they don't have to be specified in a style sheet.



回答2:


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;

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



回答3:


use  

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

Like everyone else just said.




回答4:


use a html tag 'pre'

Example:

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

result:

A line
   A line with indent


来源:https://stackoverflow.com/questions/10474696/how-to-preserve-whitespace-in-dynamically-added-javascript-dom-element-without-u

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!