如何删除表格的单元格边框?

时间:2019-04-22 05:45:05

标签: javascript html

如何通过javascript从表格中删除第一个单元格的边框? (最后是其他所示的)

        var firstRow = document.getElementById("tbl1").rows[0].cells;
        //Get first cell
        //firstRow[0].style.REMOVE CELL BORDER
        //Get 2nd row of tbl1
        var secRow = document.getElementById("tbl1").rows[1].cells;
        //Get 5th cell
        secRow[4].style.backgroundColor = 'darkBlue';
        //Get 4th row of tbl1
        var fouthRow = document.getElementById("tbl1").rows[3].cells;
        //Get 3rd, 4th and 5th cell
        fouthRow[2].style.backgroundColor = 'darkBlue';
        fouthRow[3].style.backgroundColor = 'darkBlue';
        fouthRow[4].style.backgroundColor = 'darkBlue';
        //Get 7th row of tbl1
        var seventhRow = document.getElementById("tbl1").rows[6].cells;
        //Get 2nd, 3rd cell
        seventhRow[1].style.backgroundColor = 'darkBlue';
        seventhRow[2].style.backgroundColor = 'darkBlue';

基本上,我想从表格中删除单元格。 如果有更好的方法来获得期望的结果,我很好。谢谢 Desired result

2 个答案:

答案 0 :(得分:1)

就我个人而言,我认为您应该寻找比当前硬编码版本更动态的方式。

这是一个简单的onclick和一个预先选择的功能版本:

// pre removed version
function rmPre(r,c) {
  var tbl = document.getElementById("tbl1");
  // remove border
  tbl.rows[r].cells[c].style.border = "0px";
  // remove background
  tbl.rows[r].cells[c].style.background = "transparent";
}

// onclick code
function rm(e) {
  // remove border
  this.style.border = "0px";
  // remove background
  this.style.background = "transparent";
}

window.onload = function() {
  var tbl = document.querySelector("#tbl1");
  var td = tbl.querySelectorAll("td");
  var i, max = td.length
  for(i=0;i<max;i++) {
    td[i].addEventListener("click",rm,false);
  }
  // remove onload r1,c1 and r3,c2
  rmPre(0,0);
  rmPre(2,1);
}
#tbl1 td {
 padding:0.5em;
 background:#e2edff;
 border:1px solid #000;
}
<p>
Click a cell to remove. r1,c1 and r3,c2 already removed
</p>
<table id="tbl1">
<tr>
<td>r1,c1</td><td>r1,c2</td><td>r1,c3</td>
</tr>
<tr>
<td>r2,c1</td><td>r2,c2</td><td>r2,c3</td>
</tr>
<tr>
<td>r3,c1</td><td>r3,c2</td><td>r3,c3</td>
</tr>
</table>

答案 1 :(得分:1)

针对您的问题,我提出了2个想法。

第一个:

如果您不关心单元格的对齐方式(但我相信您是..) 您可以像这样定位td

const myTable = document.querySelector('#myTable tbody')
const myRows = document.querySelectorAll('#myTable tr')
const childToRemove = myRows[0].children[0]

并按如下所示将其删除: myRows[0].removeChild(childToRemove)

但是,为了保持UI完整,我可能会采用以下解决方案:

const myTable = document.querySelector('#myTable tbody')
const myRows = document.querySelectorAll('#myTable tr')
const childToRemove = myRows[0].children[0]

childToRemove.style.borderColor = 'white'
childToRemove.style.color = 'white'
childToRemove.style.pointerEvents = 'none'

这是一个JSfiddle:https://jsfiddle.net/mkbctrlll/Lumjcy7d/35/

希望这会有所帮助