【发布时间】:2021-12-27 02:10:58
【问题描述】:
我想知道如何根据背景颜色自动反转单元格值的字体颜色以使其可读。
我使用以下脚本在将十六进制颜色代码粘贴到给定单元格How do I change a cell to the color of the hexadecimal value of a cell in Google Spreadsheets? 和sample sheet here 时自动设置背景颜色
function onEdit(e) {
r = e.range;
if(r.getSheet().getSheetName() == "colors"){ //the sheet I want to apply this to is called colors
var rows = r.getNumRows();
var columns = r.getNumColumns();
var colors = [] //this is our 2 dimensional array of colors in case you copy and paste a large amount of colors
for (var i = 1; i <= rows; i++) { //go down each row
var row = [] //create a new row array to clear the old one when we go down a row
for (var j = 1; j <= columns; j++) { //then go across each column
row.push(r.getCell(i,j).getValue()) //put together the row of colors
}
colors.push(row); //insert our row of colors so we can go down the next row
}
r.setBackgrounds(colors) //batch update in case you update many colors in one copy and paste otherwise it will be very slow
}
}
但剩下的问题是字体没有显示在深色背景单元格上。
我也发现了这个相关的问题How to decide font color in white or black depending on background color?。 还有那些带有函数的 Javascript 特定答案,但我无法让它们与 GAS 中的上述脚本一起工作。
我还查看了setFontColors(colors) 的文档,发现我们可以在上面的脚本中使用r.setFontColors(colors) 方法。
我尝试调用上面的 JavaScript 代码 1 到 6,但没有成功。
例如,我根据JavaScript code 3 尝试过这种方式):
function onEdit(e) {
r = e.range;
if(r.getSheet().getSheetName() == "colors"){ //the sheet I want to apply this to is called colors
var rows = r.getNumRows();
var columns = r.getNumColumns();
var colors = [] //this is our 2 dimensional array of colors in case you copy and paste a large amount of colors
for (var i = 1; i <= rows; i++) { //go down each row
var row = [] //create a new row array to clear the old one when we go down a row
for (var j = 1; j <= columns; j++) { //then go across each column
row.push(r.getCell(i,j).getValue()) //put together the row of colors
}
colors.push(row); //insert our row of colors so we can go down the next row
}
r.setBackgrounds(colors) //batch update in case you update many colors in one copy and paste otherwise it will be very slow
r.setFontColors(lum([111, 22, 255]));
}
}
function lum(rgb) {
var lrgb = [];
rgb.forEach(function(c) {
c = c / 255.0;
if (c <= 0.03928) {
c = c / 12.92;
} else {
c = Math.pow((c + 0.055) / 1.055, 2.4);
}
lrgb.push(c);
});
var lum = 0.2126 * lrgb[0] + 0.7152 * lrgb[1] + 0.0722 * lrgb[2];
return (lum > 0.179) ? '#000000' : '#ffffff';
}
我错过了什么?
感谢您的见解!
【问题讨论】:
标签: google-apps-script google-sheets colors rgb