只要在结果所在的 div 的 css 设置:
white-space: pre-line;//pre-wrap; pre
然后页面就能成功识别 '\n' 并整齐的显示结果了。
具体测试html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>测试textarea内容换行在div里的样式处理</title>
<style type="text/css">
textarea{
height: 200px;
}
.show-box{
/*pre的三个属性都可以达到预处理textarea的换行显示*/
white-space: pre-line;
/*white-space: pre-wrap;*/
/*white-space: pre;*/
}
</style>
</head>
<body>
<textarea onChange="getHtml(this)"></textarea>
<div id="show-box" class="show-box"></div>