html table+css实现可编辑表格

要实现可编辑的 HTML 表格,你可以使用 JavaScript 和 HTML5 的 contenteditable 属性。

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <style>
        table {
            border-collapse: collapse;
            width: 100%;
        }
        
        th, td {
            border: 1px solid black;
            padding: 8px;
            text-align: left;
        }
    </style>
</head>
<body>
    <table id="editableTable">
        <thead>
            <tr>
                <th>Name</th>
                <th>Age</th>
                <th>Gender</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td contenteditable="true">John Doe</td>
                <td contenteditable="true">25</td>
                <td contenteditable="true">Male</td>
            </tr>
            <tr>
                <td contenteditable="true">Jane Smith</td>
                <td contenteditable="true">30</td>
                <td contenteditable="true">Female</td>
            </tr>
            <!-- 添加更多行 -->
        </tbody>
    </table>

    <script>
        // 获取可编辑表格
        var table = document.getElementById('editableTable');
        
        // 遍历表格,为每个单元格添加事件侦听器
        for (var i = 0; i < table.rows.length; i++) {
            for (var j = 0; j < table.rows[i].cells.length; j++) {
                table.rows[i].cells[j].addEventListener('input', function () {
                    // 处理输入事件,可以在此处进行逻辑处理或保存数据
                    console.log(this.textContent);
                });
            }
        }
    </script>
</body>
</html>

在上述示例中,使用了 contenteditable 属性来使表格单元格可编辑。添加 contenteditable="true" 属性的单元格可以被鼠标点击并接受用户输入。

JavaScript 部分遍历表格的所有单元格,并为每个单元格添加输入事件侦听器。在输入事件处理程序中,你可以根据需要处理用户的输入,比如更新数据或触发其他操作。

点击表格前:

点击表格后:

相关推荐
人工智能训练师1 小时前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Seveny071 小时前
pnpm相对于npm,yarn的优势
前端·npm·node.js
yddddddy2 小时前
css的基本知识
前端·css
昔人'2 小时前
css `lh`单位
前端·css
破无差3 小时前
《赛事报名系统小程序》
小程序·html·uniapp
Nan_Shu_6144 小时前
Web前端面试题(2)
前端
知识分享小能手4 小时前
React学习教程,从入门到精通,React 组件核心语法知识点详解(类组件体系)(19)
前端·javascript·vue.js·学习·react.js·react·anti-design-vue
2501_918126914 小时前
用html5写一个flappybird游戏
css·游戏·html5
蚂蚁RichLab前端团队5 小时前
🚀🚀🚀 RichLab - 花呗前端团队招贤纳士 - 【转岗/内推/社招】
前端·javascript·人工智能
孩子 你要相信光5 小时前
css之一个元素可以同时应用多个动画效果
前端·css