创建自定义表格
50行代码,教你创建自定义表格!!
代码展示:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>自定义表格</title>
</head>
<body>
<center>
<div id="div" style="margin: auto;">
输入行:<input type="text" id="row" /><br>
输入列:<input type="text" id="col" /><br>
输入宽:<input type="text" id="width" /><br>
输入高:<input type="text" id="height" /><br>
<input type="button" onclick="fun();" value="创建表格" />
</div>
<script type="text/javascript">
function fun(){
var row = parseInt(document.getElementById("row").value);
var col = parseInt(document.getElementById("col").value);
var width = document.getElementById("width").value + "px";
var height = document.getElementById("height").value + "px";
//DOM文档对象:createElement创建表格
var table = document.createElement("table");
//Element元素对象:setAttribute设置属性
table.setAttribute("border","1px");
table.setAttribute("cellspacing",0);
table.setAttribute("width",width);
table.setAttribute("height",height);
//for循环:外层循环控制行,内层循环控制列
for(var i = 0;i < row; i++){
var tr = document.createElement("tr");
//判断是偶数行还是奇数行,变换颜色
if(i % 2 == 0){
tr.setAttribute("bgcolor","#00FFD0");
}else{
tr.setAttribute("bgcolor","#90FF00");
}
for(var j = 0;j < col; j++){
var td = document.createElement("td");
tr.appendChild(td);
}
table.appendChild(tr);
}
//appendChild作用:把tr存到td中,再把td存到table中,然后在id为"div"中显示出来
document.getElementById("div").appendChild(table);
}
</script>
</body>
</html>
希望读者们看完之后能自己打一遍,不要直接CV,要学习这种逻辑思想。