使用JavaScript实现表格编辑器(实例讲解)
实现效果:
html代码:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>表格编辑器</title> <link rel="stylesheet" type="text/css" href="css/tableWrite.css" rel="external nofollow" /> <script src="js/tableWrite.js" type="text/javascript" charset="utf-8"></script> </head> <body> <h1>表格编辑器</h1> <section> <table id="myTable"> <tbody> <tr> <th>用户名</th> <th>地址</th> <th>电话</th> </tr> <tr> <td>tom</td> <td>济南</td> <td>12232341</td> </tr> <tr> <td>qqq</td> <td>大时代</td> <td>213231312</td> </tr> </tbody> </table> </section> </body> </html>
Css 代码:
*{ font: 12px/25px 宋体; } h1{ font: 15px/25px 宋体; } table,th,td{ border-collapse: collapse; border: 1px solid #cccccc; }
JS 代码
function tableBlurOperator(event){ //获取事件的值 let tdvalue = event.target.value; //给事件的父类标签赋值 event.target.parentElement.value=tdvalue; } function tableClickOperator(event){ //建立一个text输入框 let input = document.createElement("input"); input.type="text"; //输入框的初始值为原标签上的值 input.value=event.target.innerHTML; //将原标签的值清空,防止出现两次 event.target.innerHTML=""; //将 text输入框加入到表格中 event.target.appendChild(input); //在最后获得焦点 input.focus(); //失去焦点的事件 input.addEventListener("blur",tableBlurOperator,false); } function init(){ //点击事件 document.getElementById("myTable").addEventListener("click",tableClickOperator,false); } window.addEventListener("load",init,false);
相关推荐
shuhaojie 2020-11-02
lerdor 2020-10-14
cakecc00 2020-09-27
iammjun 2020-09-23
MarkDownHere 2020-09-16
usepython 2020-07-20
学习web前端 2020-07-18
longzhiwen 2020-07-15
老甘的可读区 2020-07-09
zhongzhiwei 2020-07-04
maoyongfan 2020-06-28
layloge 2020-06-26
Hesland 2020-06-14
佛系程序员J 2020-06-09
老甘的可读区 2020-06-07
Kingcxx 2020-06-04
James0 2020-06-01
xiongxu 2020-05-31
pythonclass 2020-05-30