Skip to content

HTML 计算机代码

表示代码和技术输出

function greet(name) {
console.log(`Hello, ${name}!`);
}
greet('World');

HTML 提供了特定的语义化元素来表示不同类型的与计算机相关的文本,例如代码片段、键盘输入、示例输出和变量。

使用这些元素可以提高可访问性,并允许通过 CSS 进行特定的样式设置。这些元素大多数默认情况下以等宽字体呈现,从而保留了字符间距。

<code> 元素用于标记一段计算机代码。

<p>The HTML <code>&lt;section&gt;</code> element defines a section in a document.</p>
<p>In JavaScript, use the <code>console.log()</code> method for debugging.</p>

注意:<code> 元素本身不保留空白字符(例如换行符和多个空格)。对于格式很重要的代码块,请将 <code> 元素包裹在 <pre> 元素内。

<pre>:预格式化文本 (用于代码块)

Section titled “<pre>:预格式化文本 (用于代码块)”

<pre> 元素定义预格式化文本。<pre> 元素内的空白字符(空格、制表符、换行符)将完全按照 HTML 源代码中书写的方式保留。

它通常与 <code> 结合使用来显示代码块,并保持缩进和换行:

<pre><code>
function calculateArea(width, height) {
if (width > 0 && height > 0) {
return width * height;
}
return 0;
}
</code></pre>

这种组合确保代码既被语义化地标记为代码 (<code>),又被正确地视觉格式化 (<pre>)。

<kbd> 元素表示用户输入,通常来自键盘,但也可能来自语音命令或其他输入方式。

<p>To save the file, press <kbd>Ctrl</kbd> + <kbd>S</kbd>.</p>
<p>Type <kbd>exit</kbd> to close the terminal.</p>

<samp> 元素表示计算机程序或系统的示例输出。

<p>If you enter the wrong password, you might see:</p>
<p><samp>Login incorrect</samp></p>
<p>The script outputted: <samp>Process completed successfully.</samp></p>

<var> 元素表示一个变量。这可以是数学表达式或编程上下文中的变量、标识符或占位符。

<p>The area of a rectangle is calculated as <var>width</var> &times; <var>height</var>.</p>
<p>In the command <code>git commit -m "<var>message</var>"</code>, replace <var>message</var> with your commit description.</p>
标签描述
定义一段计算机代码。
定义预格式化文本(保留空白字符)。常与 <code> 一起使用。
定义键盘输入(或其他用户输入)。
定义程序示例输出。
定义变量或占位符。

适当使用这些元素可以使你的技术内容更具意义和可访问性。