[英]Type new line character in Element.TextContent
I am trying to generate a textual content in a web application. 我正在尝试在Web应用程序中生成文本内容。 I want a text to appear into a header element <h1>
but the text must contain newline breaks. 我希望文本显示在标题元素<h1>
但文本必须包含换行符。
var el = document.getElementById("myel");
var newline = "\r\n";
var nbsp = "\u00a0";
el.textContent = "My awesome" + newline + "web" + nbsp + "application";
This is not working. 这不起作用。 I mean in the developer tools, by inspecting the DOM, I can see the text being broken between "awesome"
and "web"
, but the browser does not render it that way: the text is all on the same line but at least the non breaing space (which is correctly rendered like  
) is there. 我的意思是在开发人员工具中,通过检查DOM,我可以看到文本在"awesome"
和"web"
之间被破坏,但浏览器不会这样呈现:文本全部在同一行但至少是非breaing空间(正确呈现像是 
)就在那里。
<br/>
. 尝试<br/>
。 If I try to use <br/>
, I must use innerHTML
: 如果我尝试使用<br/>
,我必须使用innerHTML
:
var el = document.getElementById("myel");
var newline = "<br/>";
var nbsp = " ";
el.innerHTML = "My awesome" + newline + "web" + nbsp + "application";
So there is no way I can get my problem solved by using textContent
? 所以我无法通过使用textContent
来解决我的问题? I would really like avoiding innerHTML
. 我真的很想避免使用innerHTML
。
Use CSS white-space: pre;
使用CSS white-space: pre;
with "\\r\\n"
: 用"\\r\\n"
:
var el = document.getElementById("myel"); var newline = "\\r\\n"; var nbsp = "\ "; el.textContent = "My awesome" + newline + "web" + nbsp + "application";
#myel { white-space: pre; }
<h1 id="myel"></h1>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.