二维码

HTML 计算机代码元素

HTML 包含多个用于定义用户输入和 计算机代码。

1
2
3
4
5
<code>  
x = 5;
y = 6;
z = x + y;
</code>

HTML <kbd> 用于键盘输入

使用 HTML 元素 定义键盘输入。里面的内容显示在浏览器的 默认等宽字体。<kbd>

1
2
3
4
5
6
7
将一些文本定义为文档中的键盘输入:

<p>Save the document by pressing <kbd>Ctrl + S</kbd></p>

结果:

Save the document by pressing Ctrl + S

HTML <samp> 用于程序输出

HTML 元素用于 定义计算机程序的示例输出。里面的内容显示在 浏览器的默认等宽字体。<samp>

1
2
3
4
5
6
7
8
9
10
11
将一些文本定义为文档中计算机程序的示例输出:

<p>Message from my computer:</p>
<p><samp>File not found.<br>Press F1 to continue</samp></p>

结果:

Message from my computer:

File not found.
Press F1 to continue

HTML <code> 用于计算机代码

使用 HTML 元素 定义一段计算机代码。里面的内容显示在 浏览器的默认等宽字体。<code>

1
2
3
4
5
6
7
8
9
10
11
12
将一些文本定义为文档中的计算机代码:

<code>
x = 5;
y = 6;
z = x + y;
</code>

结果:

`x = 5; y = 6; z = x + y;`
Press F1 to continue

请注意,该元素不保留多余的空格和换行符。<code>

要解决此问题,您可以将元素放在元素中:<code>``<pre>

1
2
3
4
5
6
7
8
9
10
11
12
13
<pre>  
<code>
x = 5;
y = 6;
z = x + y;
</code>
</pre>

结果:

`x = 5;
y = 6;
z = x + y;`

HTML <var> 用于变量

使用 HTML 元素 在编程或数学表达式中定义变量。这 里面的内容通常以斜体显示。<var>

1
2
3
4
5
6
7
将一些文本定义为文档中的变量:

<p>The area of a triangle is: 1/2 x <var>b</var> x <var>h</var>, where <var>b</var> is the base, and <var>h</var> is the vertical height.</p>

结果:

The area of a triangle is: 1/2 x b x h, where b is the base, and h is the vertical height.

本章小结

  • 该元素定义 键盘输入<kbd>
  • 该元素定义 计算机程序的示例输出<samp>
  • 该元素定义了一段计算机代码<code>
  • 该元素在编程或数学表达式中定义变量<var>
  • 该元素定义 预先格式化的文本<pre>

HTML 计算机代码元素

Tag Description
[<code>] Defines programming code
[<kbd>] Defines keyboard input
[<samp>] Defines computer output
[<var>] Defines a variable
[<pre>] Defines preformatted text

有关所有可用 HTML 标记的完整列表,请访问我们的 [HTML 标记参考]。