Bog*_* M. 1 html javascript formatting textarea
我的页面上有一个<textarea>,当我单击按钮时,textarea 中的文本值将分配给页面上某个段落的.innerHTML 。
现在假设我在文本区域中输入如下内容:
Hey
how's
it
going
?
Run Code Online (Sandbox Code Playgroud)
该段落看起来像这样
Hey how's it going ?
Run Code Online (Sandbox Code Playgroud)
基本上,每行末尾不会有<br>标签。有没有办法强制 JavaScript 函数在文本区域每行的末尾插入<br>标签,或者有更简单的方法来做到这一点?
JavaScript 代码:
document.getElementById("sendMsgBtn").onclick = function(){
var element = document.createElement("p");
element.style.borderBottom = "1px solid black";
var content = document.createTextNode(document.getElementById("currentMsg").value);
content = content.replace(/\n/g, "<br>");
element.appendChild(content);
document.body.appendChild(element);
document.getElementById("currentMsg").value = "";
}
Run Code Online (Sandbox Code Playgroud)
你不想要换行符。相信我。
只需这样设置:
white-space: pre-wrap;
Run Code Online (Sandbox Code Playgroud)
此 CSS 将使空白变得重要,并保留其输入时的样子。