我正在动态创建 H5 并渲染一个字符串。我无法创建新线路。这是我到目前为止所尝试过的:
var h5 = document.createElement('h5');
h5.appendChild(document.createTextNode("City: Chicago\nState: Illinois"));
document.body.appendChild(h5);
我也尝试过<br>
但它只是按原样呈现。如何创建新行?
最佳答案
问题
非 HTML 的换行符仅在 pre
元素和具有特殊 pre
样式的元素中呈现
解决方案
使用white-space: pre;
样式
使用单独的 CSS 规则
var h5 = document.createElement('h5');
h5.appendChild(document.createTextNode("City: Chicago\nState: Illinois"));
document.body.appendChild(h5);
h5 {
white-space: pre;
}
仅 JavaScript 解决方案
var h5 = document.createElement('h5');
h5.style.whiteSpace = 'pre';
h5.appendChild(document.createTextNode("City: Chicago\nState: Illinois"));
document.body.appendChild(h5);
希望这有帮助!
关于javascript - 换行符未在 HTML 中呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56156663/