在HTML中为 h1-h6 标签添加序号及颜色背景色块

在HTML结构中,h1h6 是常见的标题标签,通常我们会希望对这些标题进行标注或编号,使其更具层次感。在这篇文章中,我将向您展示如何通过纯JavaScript自动为 h1h6 标签添加序号,同时为这些序号添加不同的背景颜色,以突出显示层级结构。

大致效果嘛....
封面.png
并不是,其实是长下面这熊样....
demo.png

场景概述

我们有一段HTML内容,包含多个不同级别的标题标签(h1h6),如下所示:

<div id="content" class="post-content">
    <h1>大标题H1 - 1</h1>
    <h2>H2</h2>
    <h3>h3</h3>
    <h4>h4</h4>
    <h5>h5</h5> 
    <h6>h6</h6>
    <h2>H2</h2>
    <h1>大标题H1 - 2</h1>
    <h2>H2</h2>
    <h3>H3</h3>
</div>

我们的目标是:

  1. 对同一级别的标题进行独立排序,即 h1 标签从 1 开始编号,h2 标签也从 1 开始编号,依此类推。
  2. 为每个标题前的编号添加背景颜色,并且相同级别的标题背景颜色保持一致,不同级别的标题背景颜色不同。

核心技术方案

通过以下几个步骤实现:

  • 使用JavaScript:选择 h1-h6 标签,为它们添加带有编号的 span 元素。
  • 动态设置背景颜色:根据标题级别,设置不同的背景颜色。
  • 样式布局:确保编号与标题文本在视觉上良好对齐,并使用 display: flex; 保证布局不会混乱。

JavaScript 实现步骤

第一步:选择所有 h1h6 标签

我们可以使用 document.querySelectorAll() 来选择页面中的所有 h1-h6 标签,并且将它们按不同级别分组。为了确保标题级别独立排序,我们对每个级别的标题单独进行处理。

const headingLevels = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']; // 定义标题级别
headingLevels.forEach(function(level) {
    const headings = document.querySelectorAll('#content ' + level); // 获取每个级别的所有标题
});

第二步:为每个标题编号

每个标题将会有一个独立的编号。对于同级标题,每出现一个,编号递增。

let counter = 1; // 初始化编号
headings.forEach(function(heading) {
    const numberSpan = document.createElement('span');
    numberSpan.textContent = counter; // 设置编号
    counter++; // 递增编号
});

第三步:添加背景颜色和样式

根据标题的级别(h1-h6),我们为编号设置不同的背景颜色。通过JavaScript,直接为编号的 span 元素设置样式。这里我们定义了一个颜色字典,保证不同级别的标题使用不同的颜色。

const backgroundColors = {
    'h1': '#66BB6A', // Green
    'h2': '#FF7043', // Orange
    'h3': '#29B6F6', // Blue
    'h4': '#AB47BC', // Purple
    'h5': '#FFCA28', // Yellow
    'h6': '#26A69A'  // Teal
};

numberSpan.style.backgroundColor = backgroundColors[level]; // 根据标题级别设置背景颜色
numberSpan.style.color = 'white'; // 设置文本颜色为白色
numberSpan.style.padding = '5px 10px'; // 添加内边距
numberSpan.style.marginRight = '10px'; // 设置与标题文本的间距
numberSpan.style.borderRadius = '50%'; // 使其成为圆形
numberSpan.style.display = 'inline-block'; // 保证其为内联块元素

第四步:将 span 元素插入标题中

通过 prepend 方法将 span 插入到标题的最前面,使编号出现在标题的前面。

heading.prepend(numberSpan); // 将带有编号的 span 插入到标题内容的前面

完整的 JavaScript 代码

最终,我们得到完整的JavaScript代码如下:

document.addEventListener('DOMContentLoaded', function () {
    const headingLevels = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
    
    const backgroundColors = {
        'h1': '#66BB6A',
        'h2': '#FF7043',
        'h3': '#29B6F6',
        'h4': '#AB47BC',
        'h5': '#FFCA28',
        'h6': '#26A69A'
    };

    headingLevels.forEach(function(level) {
        const headings = document.querySelectorAll('#content ' + level);
        let counter = 1;
        headings.forEach(function(heading) {
            const numberSpan = document.createElement('span');
            numberSpan.textContent = counter;
            numberSpan.style.backgroundColor = backgroundColors[level];
            numberSpan.style.color = 'white';
            numberSpan.style.padding = '5px 10px';
            numberSpan.style.marginRight = '10px';
            numberSpan.style.borderRadius = '50%';
            numberSpan.style.display = 'inline-block';
            heading.prepend(numberSpan);
            counter++;
        });
    });
});

样式布局

为了确保序号和标题在视觉上保持一致,我们使用了 flex 布局。通过在 h1-h6 标签上应用 display: flex,我们可以将序号和标题文本在同一行上显示,并保证它们垂直居中对齐。

#content h1, #content h2, #content h3, #content h4, #content h5, #content h6 {
  display: flex;
  align-items: center;
}

最终效果

当我们将代码应用到页面后,浏览器会自动为每个 h1h6 标签添加带有背景色的编号。每一级标题都从 1 开始独立排序,并且序号前的圆形块使用不同的颜色。通过这种方式,用户可以更加直观地感受到标题的层次结构。

完整html

<html>
<head>
<style>
#content h1, #content h2, #content h3, #content h4, #content h5, #content h6 {
  display: flex;
  align-items: center;
}
</style>
</head>
<body>

<div id="content" class="post-content">

    <h1>大标题H1 - 1</h1>
    
    <h2>H2</h2>
    <h3>h3</h3>
    <h4>h4</h4>
    <h5>h5</h5> 
    <h6>h6</h6>
    <h2>H2</h2>
    <h1>大标题H1 - 2</h1>
    <h2>H2</h2>
    <h3>H3</h3>
</div>

<script>
  document.addEventListener('DOMContentLoaded', function () {
    // Select headings from h1 to h6
    const headingLevels = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
    
    // Define background colors for each heading level (h1 to h6)
    const backgroundColors = {
      'h1': '#66BB6A', // Green
      'h2': '#FF7043', // Orange
      'h3': '#29B6F6', // Blue
      'h4': '#AB47BC', // Purple
      'h5': '#FFCA28', // Yellow
      'h6': '#26A69A'  // Teal
    };

    // Iterate through each heading level (h1 to h6)
    headingLevels.forEach(function(level) {
      // Select all headings of the current level (e.g., all h1s, all h2s)
      const headings = document.querySelectorAll('#content ' + level);
      
      // Initialize a counter for numbering
      let counter = 1;

      // Iterate through each heading and prepend the number with a styled span
      headings.forEach(function(heading) {
        // Create the number span element
        const numberSpan = document.createElement('span');
        numberSpan.textContent = counter; // Add the number
        numberSpan.style.backgroundColor = backgroundColors[level]; // Set the background color for the current level
        numberSpan.style.color = 'white'; // Make text white
        numberSpan.style.padding = '5px 10px'; // Add padding around the number
        numberSpan.style.marginRight = '10px'; // Add some spacing between the number and the heading text
        numberSpan.style.borderRadius = '50%'; // Make it circular
        numberSpan.style.display = 'inline-block'; // Ensure it's displayed inline
        
        // Prepend the number span to the heading
        heading.prepend(numberSpan);

        // Increment the counter for the next heading of the same level
        counter++;
      });
    });
  });
</script>
</body>
</html>

标签: CSS, Javascript

相关文章

VUE倒计时组件

常用于发送短信、邮件后1分钟倒计时,倒计时结束后又可以再次点击vue组件封装:<template> <div class="timer-btn">...

图片Base64编码

CSR生成

图片无损放大

图片占位符

Excel拆分文件