1分钟搞定table表单的双击编辑功能
实现思路( 代码并不重要,关键是思路 )
1.当你看到页面时,是普通的table表单,且正常情况不能编辑。当你双击的时候就进入编辑状态,这样在展示到页面上的时候给人一种普通table表单却能直接编辑的假象。 实际是在一个属性为text且隐藏起来的input标签上编辑,给table表单的单元格绑定了双击事件,触发时创建input标签并显示,并且同时将选中的table表单单元格上对应的值赋值给了input标签,当输入回车或者失去焦点时,通过赋值将相应的数据回填到单元格且隐藏input标签来完成修改。
参照流程图理解:
css代码
* {
text-align: center;
font-size: 18px;
}
table {
border: 1px solid #eee;
}
th {
background-image: linear-gradient(skyblue, #fff);
}
td {
position: relative;
background-image: linear-gradient(pink, #fff);
}
input {
position: absolute;
top: 0;
left: 0;
display: none;
width: 100%;
height: 100%;
background-image: linear-gradient(pink, #fff);
border: none;
outline: medium;
}
html代码
<table>
<colgroup>
<col width="14%" />
<col width="16%" />
<col width="15%" />
<col width="15%" />
<col width="15%" />
<col width="15%" />
<col width="15%" />
</colgroup>
<thead>
<tr>
<th scope="col">学员ID</th>
<th scope="col">姓名</th>
<th scope="col">第1次成绩</th>
<th scope="col">第2次成绩</th>
<th scope="col">第3次成绩</th>
<th scope="col">第4次成绩</th>
<th scope="col">第5次成绩</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">10</th>
<td>张三</td>
<td class="score">70</td>
<td class="score">70</td>
<td class="score">70</td>
<td class="score"></td>
<td class="score"></td>
</tr>
<tr>
<th scope="row">11</th>
<td>李四</td>
<td class="score">70</td>
<td class="score">70</td>
<td class="score"></td>
<td class="score"></td>
<td class="score"></td>
</tr>
</tbody>
</table>
js代码
// 给成绩单元格绑定双击事件
document
.querySelector("tbody")
.addEventListener("dblclick", function (e) {
if (e.target.classList.contains("score")) {
const input = document.createElement("input");
input.type = "text";
e.target.append(input);
// 标签显示出来
input.style.display = "block";
input.value = e.target.innerText; // 显示旧成绩
// 让input标签自动获得焦点
input.focus();
// 给input绑定抬起键盘 判断按下是不是回车键,如果是回车就回填
input.addEventListener("keyup", function (ev) {
if (ev.key === "Enter") {
e.target.innerText = input.value;
input.style.display = "none";
}
});
//设置失焦回填内容
input.addEventListener("blur", function (ev) {
e.target.innerText = input.value;
input.style.display = "none";
});
}
});