繁体   English   中英

根据值更改单元格背景颜色?

[英]Change cell background color based on value?

我有这个 function 接收一个二维数组并创建一个表。 我想根据单元格中的值更改单元格背景颜色。 前任。 (如果 cellVal > 0 将背景更改为绿色)

//function to create the table
function createTable(tableData) {
  var table = document.createElement('table');
  var row = {};
  var cell = {};

  tableData.forEach(function (rowData) {
    row = table.insertRow(-1);
    rowData.forEach(function (cellData) {
      cell = row.insertCell();

      cell.textContent = cellData;
    });
  });
  document.body.appendChild(table);
}
createTable(transpose_array)

//css
td {
  border: 1px solid black;
  padding: 4px;
  text-align: center;
  vertical-align: middle;
  width: 20px;
  height: 20px;
}
table {
    border-collapse: collapse;
    border-spacing: 0;

}

 let transpose_array = [ [['a', 3], ['b', -2], ['c', 4]], [[1, -3], [2, 2], [3, -1]] ] function createTable(tableData) { var table = document.createElement('table'); let row; let cell; tableData.forEach(function (rowData) { row = table.insertRow(-1); rowData.forEach(function (cellData) { cell = row.insertCell(); cell.textContent = cellData[0]; let cellVal = cellData[1]; if (cellVal > 0) { cell.classList.add('green') } }); }); document.body.appendChild(table); } createTable(transpose_array)
 .green { background-color: green; }

tableData.forEach(function (rowData,i) {
    row = table.insertRow(-1);
    cell = row.insertCell();
    cell.textContent = row_headings[i];

    rowData.forEach(function (cellData) {
      cell = row.insertCell();
      cell.textContent = cellData;
      let cellVal = cellData;
      //make cells different shaeds of green and red for pos/neg (based on %)
      if (cellVal > 0) {
        cell.style.backgroundColor = '#00e100';
      } else if (cellVal < 0) {
        cell.style.backgroundColor = 'red';
      }
    });
  });
 document.body.appendChild(table);

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM