一、首先是控制行的前插直贴代码
var tr = td.parentNode; //obj.parentNode.parentNode是<tr>
var table = tr.parentNode; //tr.parentNode是<table>
var y = table.rows.length;
var oldRow = tr;
if (oldRow) {
var newRow = oldRow.cloneNode(true); //拷贝一行项到另外一行
}
var index = tr.rowIndex;
var newTr = table.insertRow(index);
newTr.setAttribute("style", tr.getAttribute("style"));
for (var i = 0; i < tr.childNodes.length; i++) {
var newtd = newTr.insertCell();
newtd.setAttribute(
"style",
td.parentNode
.querySelectorAll("td")
[i].getAttribute("style")
);
newtd.setAttribute("contenteditable", true);
newtd.setAttribute(
"colspan",
td.parentNode
.querySelectorAll("td")
[i].getAttribute("colspan")
);
}
因为是在线编辑html,所以样式也要加上。
二、删除行
var tr = td.parentElement;
var tbody = tr.parentElement;
tbody.removeChild(tr);
三、删除列
var tr = td.parentElement;
var cellindex=td.cellIndex;//获取当前单元格的下标
var tb=tr.parentElement;
var rowindex=tr.rowIndex;//当前hang数
var rows=tb.rows;//hang数
var cos_1=parseInt(tb.rows[rowindex].cells[cellindex].getAttribute('colspan')) ;
for(var i=0;i<rows.length;i++){
var bd=rows[i].cells[1].style.borderLeft;
if(bd==""){
continue;
}
if(cellindex>=rows[i].cells.length-1){
continue;
}
var cos=parseInt(tb.rows[i].cells[cellindex].getAttribute('colspan'));//获取要删除的合并航
var bool=isNaN(cos);
if(bool){
cos=1;
}
tb.rows[i].deleteCell(cellindex);
rows[i].cells[rows[i].cells.length-2].setAttribute('colspan',parseInt(rows[i].cells[rows[i].cells.length-2].getAttribute('colspan'))+cos );
}
四、列的前插就复杂了,我这里是根据项目表格逻辑写的,
var cellindex=td.cellIndex;//获取当前单元格的下标
var oldcell=td;
var newRow=oldcell.cloneNode(true); //拷贝单元格
var tb=td.parentElement.parentElement;
var rows=tb.rows;//hang数
if(data.value==1){
for(var i=0;i<rows.length;i++){
var bd=rows[i].cells[1].style.borderLeft;
if(bd==""){
//不加列的行将最后cosplan+1
console.log(rows[i].cells[rows[i].cells.length-1].getAttribute('colspan'));
rows[i].cells[rows[i].cells.length-1].setAttribute('colspan',parseInt( rows[i].cells[rows[i].cells.length-1].getAttribute('colspan')==null?1:rows[i].cells[rows[i].cells.length-1].getAttribute('colspan'))+1);
continue;
}
//开始行和最后行
if(cellindex>=rows[i].cells.length-1){
rows[i].cells[rows[i].cells.length-2].setAttribute('colspan',parseInt( rows[i].cells[rows[i].cells.length-2].getAttribute('colspan'))+1);
// rows[i].cells[rows[i].cells.length-1].setAttribute('colspan',3);
continue;
}
var x=tb.rows[i].insertCell(cellindex);
x.setAttribute('style',td.getAttribute('style'));
x.setAttribute('contenteditable',true);
x.setAttribute('rowspan',td.getAttribute('rowspan'));