Skip to content

第8章:代码块与代码高亮

8.1 行内代码

行内代码用于在文本中嵌入代码片段,在Markdown中,使用反引号 ` 包裹代码内容。

语法

markdown
`代码内容`

示例

markdown
在终端中输入 `git status` 命令查看仓库状态。

函数 `print()` 用于输出内容到控制台。

适用场景

  • 代码关键词:在文本中引用代码中的关键词或变量名
  • 简单代码片段:嵌入简短的代码片段,如函数名、变量名等
  • 命令行指令:展示终端命令或脚本指令

8.2 代码块

代码块用于展示多行代码,在Markdown中,使用三个反引号 ``` 包裹代码内容。

基础语法

语法

markdown

代码内容 代码内容

示例

markdown

def hello(): print("Hello, Markdown!")

hello()

代码高亮

为了使代码更加美观和易读,你可以指定编程语言,实现语法高亮。

语法

markdown
```语言
代码内容

**示例**:
```markdown
```python
def hello():
    print("Hello, Markdown!")

hello()

### 常用编程语言高亮

Markdown支持多种编程语言的语法高亮,以下是一些常用的编程语言:

- **Python**:`python`
- **JavaScript**:`javascript` 或 `js`
- **Java**:`java`
- **C++**:`cpp` 或 `c++`
- **C#**:`csharp` 或 `cs`
- **HTML**:`html`
- **CSS**:`css`
- **SQL**:`sql`
- **Bash**:`bash` 或 `shell`
- **JSON**:`json`
- **YAML**:`yaml` 或 `yml`

**示例**:

```markdown
```javascript
function hello() {
    console.log("Hello, Markdown!");
}

hello();
html
<!DOCTYPE html>
<html>
<head>
    <title>Markdown Example</title>
</head>
<body>
    <h1>Hello, Markdown!</h1>
</body>
</html>
css
body {
    font-family: Arial, sans-serif;
    background-color: #f0f0f0;
}

h1 {
    color: #333;
}

### 代码块换行与缩进

在代码块中,你可以保持代码的原始格式,包括换行和缩进,Markdown会保留这些格式。

**示例**:
```markdown
```python
# 计算斐波那契数列
def fibonacci(n):
    if n <= 1:
        return n
    else:
        return fibonacci(n-1) + fibonacci(n-2)

# 输出前10个斐波那契数
for i in range(10):
    print(fibonacci(i))

## 8.3 命令行代码块

命令行代码块用于展示终端命令和输出,使用 `bash` 或 `shell` 作为语言标识符。

**语法**:
```markdown
```bash
命令

**示例**:
```markdown
```bash
# 查看当前目录
pwd

# 列出文件
ls -la

# 安装依赖
npm install

# 运行项目
npm start

## 实操案例:添加代码块

### 示例文档

```markdown
# 代码示例

## 行内代码

在Python中,使用 `print()` 函数输出内容。

在JavaScript中,使用 `console.log()` 函数输出内容。

## 代码块

### Python代码

```python
def calculate_area(radius):
    """计算圆的面积"""
    import math
    return math.pi * radius ** 2

# 测试函数
radius = 5
area = calculate_area(radius)
print(f"半径为 {radius} 的圆的面积为: {area:.2f}")

JavaScript代码

javascript
// 计算圆的面积
function calculateArea(radius) {
    return Math.PI * Math.pow(radius, 2);
}

// 测试函数
const radius = 5;
const area = calculateArea(radius);
console.log(`半径为 ${radius} 的圆的面积为: ${area.toFixed(2)}`);

HTML代码

html
<!DOCTYPE html>
<html>
<head>
    <title>圆的面积计算器</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        input { padding: 8px; margin: 10px 0; }
        button { padding: 10px 20px; background-color: #4CAF50; color: white; border: none; }
        #result { margin-top: 20px; font-size: 18px; }
    </style>
</head>
<body>
    <h1>圆的面积计算器</h1>
    <input type="number" id="radius" placeholder="请输入半径">
    <button onclick="calculate()">计算面积</button>
    <div id="result"></div>
    
    <script>
        function calculate() {
            const radius = document.getElementById('radius').value;
            const area = Math.PI * Math.pow(radius, 2);
            document.getElementById('result').textContent = `半径为 ${radius} 的圆的面积为: ${area.toFixed(2)}`;
        }
    </script>
</body>
</html>

命令行代码

bash
# 创建项目目录
mkdir my-project
cd my-project

# 初始化项目
npm init -y

# 安装依赖
npm install express

# 创建服务器文件
echo "const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(3000, () => { console.log('Server running on port 3000'); });" > server.js

# 启动服务器
node server.js

### 效果预览

通过上面的操作,你应该可以看到一个包含各种代码块的Markdown文档,代码块有语法高亮,格式清晰。

## 新手易错点

### 反引号遗漏

- **错误**:只使用了一个反引号,而不是三个反引号
- **错误**:代码块的开始和结束反引号数量不一致

### 编程语言指定错误

- **错误**:指定了不支持的编程语言
- **错误**:编程语言名称拼写错误

### 代码格式错乱

- **错误**:在代码块中混合了Markdown语法
- **错误**:代码缩进不一致,影响可读性

### 命令行代码块错误

- **错误**:在命令行代码块中没有使用 `bash` 或 `shell` 作为语言标识符
- **错误**:命令行代码块中包含了非命令行内容

## 练习建议

- 尝试添加不同编程语言的代码块
- 练习使用行内代码和代码块
- 尝试添加命令行代码块
- 注意保持代码的格式和缩进
- 测试代码块的语法高亮效果

通过练习,你应该能够熟练掌握Markdown代码块的使用方法,创建包含代码示例的技术文档。

© 2026 编程马·菜鸟教程 版权所有