我希望这段代码的所有刺痛都在单独的行上,但它都在一行上。我已经尝试了r
和n
以下是前几行:
document.write("you are an explorer, entering a dragons cavern in hopes of treasure");
document.write("be warned, the caverns are always changing");
document.write("...");
\r 和 用于文档中的换行符,这对于呈现的内容 (html) 无关紧要,除非您在 <pre>
标记内或使用 CSS 属性whitespace
来呈现文档空格。在 html 中,换行符是 <br>
。
虽然 <br>
标签有时很有用,但不要无缘无故地使用它。例如,如果要拆分两个paragragh,则会有如下所示的标记:
<p>This is paragraph 1.</p>
<p>This is paragraph 2.</p>
要在它们之间留出一个空格,您可以使用 css 样式:
p {
display: block;
margin-botton: 20px;
}
在这种情况下,您不应像这样使用 <br>
标记:
<p>This is paragraph 1.</p>
<br>
<p>This is paragraph 2.</p>
另请注意,document.write
是一种危险的做法,几乎从来都不是必需的。与其使用 document.write,不如使用 javascript 来创建/操作如下所示的元素:
var p = document.createElement('p');
p.textContent = 'This is paragraph 1.';
document.body.appendChild(p);
document.write
生成HTML。空格在 HTML 中压缩,因此如果您需要换行符,则需要使用 <br>
元素。
document.write("you are an explorer, entering a dragons cavern in hopes of treasure<br>");
document.write("be warned, the caverns are always changing<br>");
document.write("...<br>");
此外,无需将document.write
字符串分解为多个调用:
document.write('you are an explorer, entering a dragons cavern in hopes of treasure<br>be warned, the caverns are always changing<br>...');
一般来说,document.write
应该不鼓励,因为在文档关闭写入后调用它会重写整个页面。通常,这些类型的更改是通过 DOM 节点完成的:
document.body.innerHTML = 'you are an explorer, entering a dragons cavern in hopes of treasure<br>be warned, the caverns are always changing<br>...';
或者,如果需要保证文本的格式,可以使用 <pre>
元素(或带有 white-space: pre
的 CSS)。预先格式化的文本允许使用换行符和多个空格:
<pre>you are an explorer, entering a dragons cavern in hopes of treasure
be warned, the caverns are always changing
...</pre>
如果必须使用 document,请使用 document.writeln 而不是 document.write
使用 HTML 标记:
document.write("<p>you are an explorer, entering a dragons cavern in hopes of treasure</p>");
document.write("<p>be warned, the caverns are always changing</p>");
document.write("<p>...</p>");
使用document.write();
时,您需要意识到这是它正在生成的HTML,因此,您应该使用<br>
来创建所需的结果。 此外,这种方法并不是很受欢迎。