我正在动态创建H5并渲染一个String。我无法创建新行。到目前为止,这是我尝试过的:
var h5 = document.createElement('h5');
h5.appendChild(document.createTextNode("City: Chicago\nState: Illinois"));
document.body.appendChild(h5);
我也尝试过<br>
,但它只是按原样呈现。如何创建新行?
答案 0 :(得分:4)
不是HTML的换行符仅以pre
元素和具有特殊pre
样式的换行符呈现
使用white-space: pre;
风格
var h5 = document.createElement('h5');
h5.appendChild(document.createTextNode("City: Chicago\nState: Illinois"));
document.body.appendChild(h5);
h5 {
white-space: pre;
}
var h5 = document.createElement('h5');
h5.style.whiteSpace = 'pre';
h5.appendChild(document.createTextNode("City: Chicago\nState: Illinois"));
document.body.appendChild(h5);
希望这会有所帮助!
答案 1 :(得分:2)
textnode元素不解释html,这就是为什么您的html被编写为文本的原因。 另一方面,\ n将插入到textnode中,但在html H5标签中不起作用。一种解决方案是创建一个“ pre”标签而不是h5,或使用innerHTMl属性...
var h5 = document.createElement('h5');
h5.innerHTML="City: Chicago<br>State: Illinois";
document.body.appendChild(h5);