[英]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>
您必須將row
和col
變量加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.