【问题标题】:How do I change the background colour of a cell programically? (not onchange, not depending on value, not on creation)如何以编程方式更改单元格的背景颜色? (不依赖于变化,不依赖于价值,不依赖于创造)
【发布时间】:2018-06-26 13:15:39
【问题描述】:

我在互联网上研究过这个问题,但我找不到答案。

我想更改特定可操作单元格的背景颜色。请注意,我不是指在创建可动手做对象时设置颜色,也不是在更改表中的值后设置颜色。

理想情况下,我可以这样做:(下面的伪代码)

function setColour(row,col,colour){
  hot.cells(row,col).backgroundColour=colour
 }

function makeItRed(){
  setColour(0,4,"#FF0000") //this sets the cell in the 1st row and 5th column to red
}

有没有办法做到这一点?

编辑:

出于问题的目的,请假设makeItRed() 函数调用将分配给一个按钮。

编辑2: Stackoverflow 不允许将技术名称放在问题标题中,它是关于 HANDSONTABLE 而不是 HTML 表。

【问题讨论】:

  • 也许是因为这个问题没有意义。您要回答的一个问题是什么时候?
  • @Adam Azad。当我调用 makeItRed() 函数时。我的问题有什么不清楚的地方?
  • 但这需要一个事件来调用它,例如按钮单击或对环境变化的响应。
  • 请假设它将被分配给一个按钮,尽管我不知道无论是分配给一个按钮、从控制台手动调用还是在计时器上,答案都会有所不同。

标签: javascript handsontable


【解决方案1】:

您可以使用:nth-child() 选择器来做到这一点:

https://repl.it/@ryanpcmcquen/PricklyJumboBlackbear

document.addEventListener('DOMContentLoaded', () => {
    const setColour = (row, col, colour) => {
        const cell = document.querySelector(`table tr:nth-child(${row + 1}) td:nth-child(${col + 1})`);
        cell.style.backgroundColor = colour;
    };
    
    const makeItRed = () => {
        setColour(0, 2, "#FF0000");
    };
    
    document.querySelector('.color-me').addEventListener('click', () => {
        makeItRed();
    });
});
table, table tr, table td {
    border-style: solid;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="index.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
      <table>
          <tr>
              <td>0, 0</td>
              <td>0, 1</td>
              <td>0, 2</td>
          </tr>
          <tr>
              <td>1, 0</td>
              <td>1, 1</td>
              <td>1, 2</td>
          </tr>
      </table>
      <br />
      <button class="color-me">Color me</button>
    <script src="index.js"></script>
  </body>
</html>

您必须将 rowcol 变量加 1,因为 :nth-child() 不是从零开始的。

【讨论】:

  • 问题是关于handsontable
  • @LucasSeveryn,这仍然有效。 Handsontable 仍然构建一个 HTML 表格。相同的规则适用。
【解决方案2】:

Handsontable 允许您设置一个 custom renderer 来为您的背景着色:

const bgRenderer = function(instance, td, row, col, prop, value, cellProperties) {
    Handsontable.renderers.TextRenderer.apply(this, arguments);
    td.style.backgroundColor = '#cbd9e4';
};

function makeItRed() {
    hot.getCellMeta(0,0).renderer = bgRenderer;
    hot.render();
};

如果您使用其他渲染器(如Handsontable.renderers.DateRenderer),您也需要覆盖它们。

完整示例here

顺便说一句,@ryanpcmcquen 的着色方式会起作用,但背景不会粘住 - 请参阅相同的 jfiddle。

【讨论】:

  • 这是否意味着我必须为我可能想要使用的每种颜色创建一个自定义渲染器?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-06
  • 1970-01-01
  • 2021-11-19
  • 2019-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多