繁体   English   中英

如何以编程方式更改单元格的背景颜色? (不改变,不依赖于价值,不依赖于创造)

[英]How do I change the background colour of a cell programically? (not onchange, not depending on value, not on creation)

我已经在互联网上研究了该问题,但找不到答案。

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

理想情况下,我可以执行以下操作:(下面的伪代码)

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()函数调用分配给按钮。

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

您可以使用: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允许您设置将为背景着色的自定义渲染器

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 ),则也需要覆盖它们。

这里完整的例子。

顺便说一句,@ ryanpcmcquen的上色方法可以使用,但背景不会停留-看到相同的jfiddle。

暂无
暂无

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

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