今天给大家弄一个很有意思东西!
怎样实现表格换色?
话不多说直接上素材;
下面是我搞的示例,大家可以看一下;
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>标准</title> <style> table { width: 300px; border: 1px #525252 solid; } th, td { border: 1px #525252 solid; text-align: center; } </style> </head> <body> <table cellspacing="0"> <thead> <tr> <th>序号</th> <th>内容</th> <th>操作</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>data</td> <td> <button>删除</button> </td> </tr> </tbody> </table> <button id="but">添加行</button> <script src="表格隔行换色.JS"></script> </body> </html>
以上是表格基本样式,我使用的是内嵌方式。
let but = document.getElementById("but"); let thead = document.getElementsByTagName("thead")[0]; let tbody = document.getElementsByTagName('tbody')[0]; let content = 100; but.onclick = function() { let theadtr = thead.getElementsByTagName("tr")[0]; let ths = theadtr.children; let newtr = document.createElement("tr"); for (let i = 0; i < ths.length; i++) { let newtd = document.createElement("td"); let tbodytr = tbody.children; if (i == 0) { newtd.innerHTML = tbodytr.length + 1; } if (i == 1) { newtd.innerHTML = content; content += 100; } if (i == ths.length - 1) { newtd.innerHTML = "<button>删除</button>"; } newtr.appendChild(newtd); } tbody.appendChild(newtr); cutcolor(); } function cutcolor() { let trs = tbody.children; for (let i = 0; i < trs.length; i++) { if (i % 2 == 1) { trs[i].style.backgroundColor = "green"; } else { trs[i].style.backgroundColor = "#FFFFFF"; } } //取余数偶数上色,奇数不上色 } tbody.addEventListener("click", function(e) { e = e || window.event; let target = e.target || e.srcElement; if (target.innerHTML == "删除") { let istr = target.parentElement.parentElement; tbody.removeChild(istr); issort(); cutcolor(); //删除 } }) function issort() { let trs = tbody.children; for (let i = 0; i < trs.length; i++) { let trstd = trs[i].children[0]; trstd.innerHTML = i + 1; } }
这是写在JS里的代码,是用来操控数据的。
好了今天给大家分享的挺有意思的,还请大家多多关照,点一个不要钱的赞!