【问题标题】:Paragraph with multiple font colors vs. paragraph with an unset font color?具有多种字体颜色的段落与具有未设置字体颜色的段落?
【发布时间】:2021-05-25 23:10:58
【问题描述】:

在我的 Google Apps 脚本中,我只想在整个段落已经是黑色的情况下更改文本颜色。我可以很容易地做到这一点:

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

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

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

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

【问题讨论】:

    标签: javascript google-apps-script google-docs


    【解决方案1】:

    我相信你的目标如下。

    • 当段落中所有字符的字体颜色为#000000时,要将段落的字体颜色设置为#ffffff
    • 例如,当段落中部分文本的字体颜色不是#000000时,您不想更改段落的字体颜色。
    • 您希望使用 Google Apps 脚本实现此目的。

    修改点:

    • 在当前阶段,当文本为#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");
          }
        });
    }
    

    参考:

    【讨论】:

      【解决方案2】:

      作为对 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 循环应该更快。大概some()这个函数已经优化好了。

      【讨论】:

        猜你喜欢
        • 2018-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多