javascript - 如何在单个字符串中在javascript中创建一个新行

标签 javascript html

正如您在我的 index.html 文件中看到的那样,我正在尝试创建新行(在这一行文本中),但它不起作用,有什么帮助吗? (\n 是新行应该开始的地方,
也没有用。

index.html:

<html>
        <head>
                <title>test</title>
        </head>
<body bgcolor="black">
<font color="green">
<p id="terminal"></p>
<script>
var text = "this is a test\nthis should be on the next line";
var count = 0;
var speed = 50;
function Type() {
        if(count < text.length) {
                document.getElementById("terminal").innerHTML += text.charAt(count);
                count ++;
                setTimeout(Type, speed);
        }
}
Type();
</script>

最佳答案

如果你不想使用<br />您可以轻松使用 <pre>标签。 <pre>其实更容易使用因为您不必插入 <br />在 DOM 中的正确位置。

取自docs .

The HTML pre element represents preformatted text which is to be presented exactly as written in the HTML file.

var text = "this is a test\nthis should be on the next line";
var count = 0;
var speed = 50;

function Type() {
    if(count < text.length) {
        document.getElementById("terminal").innerHTML += text.charAt(count);
        count ++;
        setTimeout(Type, speed);
    }
}
Type();
<html>
  <head>
    <title>test</title>
  </head>
  <body bgcolor="black">
    <font color="green" />
    <pre id="terminal"></pre>
  </body>
</html>

关于javascript - 如何在单个字符串中在javascript中创建一个新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49637842/

相关文章:

javascript - 使用 ui-router 时,自定义指令在嵌套 View 中不活动

javascript - ReactJS 状态在第二次 onChange 时更新

php - 嵌入式视频不显示

html - 尽管没有内容,但使容器 100% 高度

javascript - HTML 和 JavaScript 的执行顺序是什么?

javascript - JS 回调函数可以返回值吗?

javascript - 未设置对象的数据成员值

regex - 电话号码的自定义 html5 验证正则表达式

javascript - 这两个比较有什么区别?

html - 使用 CSS3 自动滚动溢出文本