菜鸟-创作你的创作

html table+css实现可编辑表格的示例代码 

以下是一个使用 纯 HTML + CSS + 少量 JavaScript 实现的可编辑表格示例,支持:

html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>可编辑 HTML 表格</title>
  <style>
    body {
      font-family: Arial, Helvetica, sans-serif;
      margin: 40px;
      background: #f5f5f5;
    }

    .container {
      max-width: 900px;
      margin: 0 auto;
    }

    table {
      width: 100%;
      border-collapse: collapse;
      background: white;
      box-shadow: 0 2px 10px rgba(0,0,0,0.1);
      border-radius: 8px;
      overflow: hidden;
    }

    th, td {
      padding: 12px 15px;
      text-align: left;
      border-bottom: 1px solid #ddd;
    }

    th {
      background-color: #4a90e2;
      color: white;
      font-weight: bold;
    }

    tr:hover {
      background-color: #f8f9fa;
    }

    td.editable {
      cursor: pointer;
      position: relative;
    }

    td.editable:hover {
      background-color: #e3f2fd;
    }

    /* 编辑状态下的输入框 */
    td.editing input {
      width: 100%;
      padding: 6px 8px;
      border: 2px solid #4a90e2;
      border-radius: 4px;
      outline: none;
      font-size: 1em;
    }

    /* 操作按钮 */
    .actions {
      text-align: center;
    }

    button {
      padding: 6px 12px;
      margin: 0 4px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 0.9em;
    }

    .btn-add {
      background: #28a745;
      color: white;
    }

    .btn-delete {
      background: #dc3545;
      color: white;
    }

    .btn-save {
      background: #17a2b8;
      color: white;
    }
  </style>
</head>
<body>
  <div class="container">
    <h2>可编辑表格示例</h2>

    <button class="btn-add" onclick="addRow()">+ 添加一行</button>

    <table id="editableTable">
      <thead>
        <tr>
          <th>姓名</th>
          <th>年龄</th>
          <th>城市</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td class="editable" data-field="name">张三</td>
          <td class="editable" data-field="age">28</td>
          <td class="editable" data-field="city">北京</td>
          <td class="actions">
            <button class="btn-delete" onclick="deleteRow(this)">删除</button>
          </td>
        </tr>
        <tr>
          <td class="editable" data-field="name">李四</td>
          <td class="editable" data-field="age">34</td>
          <td class="editable" data-field="city">上海</td>
          <td class="actions">
            <button class="btn-delete" onclick="deleteRow(this)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>

  <script>
    // 点击单元格进入编辑模式
    document.querySelectorAll('.editable').forEach(cell => {
      cell.addEventListener('click', function() {
        if (this.classList.contains('editing')) return;

        const originalValue = this.textContent.trim();
        const input = document.createElement('input');
        input.type = 'text';
        input.value = originalValue;

        // 清空并放入 input
        this.textContent = '';
        this.appendChild(input);
        this.classList.add('editing');

        // 自动聚焦
        input.focus();

        // Enter 保存,Esc 取消
        input.addEventListener('keydown', function(e) {
          if (e.key === 'Enter') {
            saveEdit(cell, input.value);
          } else if (e.key === 'Escape') {
            cancelEdit(cell, originalValue);
          }
        });

        // 失去焦点也保存
        input.addEventListener('blur', () => {
          saveEdit(cell, input.value);
        });
      });
    });

    // 保存编辑
    function saveEdit(cell, newValue) {
      cell.textContent = newValue.trim() || '—';
      cell.classList.remove('editing');
    }

    // 取消编辑
    function cancelEdit(cell, originalValue) {
      cell.textContent = originalValue;
      cell.classList.remove('editing');
    }

    // 添加新行
    function addRow() {
      const table = document.getElementById('editableTable').getElementsByTagName('tbody')[0];
      const newRow = table.insertRow();

      // 创建可编辑单元格
      ['name', 'age', 'city'].forEach(field => {
        const cell = newRow.insertCell();
        cell.className = 'editable';
        cell.dataset.field = field;
        cell.textContent = '点击编辑';
        // 重新绑定点击事件
        cell.addEventListener('click', function() {
          // 复用上面的点击逻辑(可提取为函数更优雅)
          if (this.classList.contains('editing')) return;
          const originalValue = this.textContent.trim();
          const input = document.createElement('input');
          input.value = originalValue;
          this.textContent = '';
          this.appendChild(input);
          this.classList.add('editing');
          input.focus();

          input.addEventListener('keydown', e => {
            if (e.key === 'Enter') saveEdit(this, input.value);
            if (e.key === 'Escape') cancelEdit(this, originalValue);
          });
          input.addEventListener('blur', () => saveEdit(this, input.value));
        });
      });

      // 操作列
      const actionCell = newRow.insertCell();
      actionCell.className = 'actions';
      actionCell.innerHTML = `<button class="btn-delete" onclick="deleteRow(this)">删除</button>`;
    }

    // 删除行
    function deleteRow(btn) {
      if (confirm('确定删除此行?')) {
        const row = btn.closest('tr');
        row.remove();
      }
    }
  </script>
</body>
</html>

主要特点说明:

进阶建议(根据需求可扩展):

  1. 数据持久化 → 结合 localStorage 保存
  2. 字段校验 → 在保存时用正则校验年龄是否为数字
  3. 批量操作 → 添加多选删除、全选功能
  4. 样式美化 → 引入 Tailwind CSS 或 Element Plus 风格
  5. 真实数据 → 通过 fetch 从后端加载 JSON 数据

需要更复杂的功能(如排序、过滤、分页、导出 Excel 等)也可以告诉我,我再帮你扩展!

退出移动版