具有多种字体颜色的段落与具有未设置字体颜色的段



在我的谷歌应用程序脚本中,只有当整个段落已经是黑色时,我才想更改文本的颜色。我可以很容易地做到这一点:

if (currentPar.editAsText().getForegroundColor() === "#000000") {
currentPar.setForegroundColor("#ffffff");
}

我遇到的问题是,从技术上讲,文档中的大多数黑色文本都是未设置的,这意味着currentPar.editAsText().getForegroundColor()返回null

我尝试将|| currentPar.editAsText().getForegroundColor() === null添加到条件中,但对于在同一段落中使用多种颜色的情况,它也会返回true。

有没有办法区分null的两种情况?

我相信你的目标如下。

  • 当段落中所有字符的字体颜色为#000000时,您需要将段落的字体颜色设置为#ffffff
  • 例如,当段落中某部分文本的字体颜色不是#000000时,您不希望更改该段落的字体颜色
  • 你想使用谷歌应用程序脚本来实现这一点

修改点:

  • 在当前阶段,当文本为#000000的默认字体颜色时,getForegroundColor()返回null。而且,似乎即使段落中的文本部分不是#000000的颜色,也会返回null。(例如,当一段中的所有字符都是相同的颜色,如红色时,返回#ff0000。(这似乎是当前的规范
  • 为了实现您的目标,在这个答案中,我想使用getForegroundColor(offset)检查段落中每个字符的字体颜色

当上面的点反映到脚本中时,它变成如下。

示例脚本:

function myFunction() {
DocumentApp
.getActiveDocument()
.getBody()
.getParagraphs()
.forEach(p => {
const text = p.editAsText();
let c = true;
for (let i = 0; i < text.getText().length; i++) {
if (text.getForegroundColor(i) != null) {
c = false;
break;
}
}
if (c) {
text.setForegroundColor("#ffffff");
}
});
}

参考:

  • getForegroundColor(偏移量(

作为Tanaike出色答案的补充,我刚刚发现对他的算法的修改工作得更快:

function myFunction() {
DocumentApp
.getActiveDocument()
.getBody()
.getParagraphs()
.forEach(p => {
const text = p.editAsText();
const colors = text.getText().split("").map((_,i) => text.getForegroundColor(i));
if (!colors.some(x => x != null)) text.setForegroundColor("#fffff");
});
}

这看起来违反直觉。使用break的循环应该工作得更快。可能函数CCD_ 16被很好地优化了。

最新更新