如何使用脚本在Google文档中设置文本格式 [英] How to format text in Google Docs using script

查看:123
本文介绍了如何使用脚本在Google文档中设置文本格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个脚本来查找所有特定单词并设置其颜色格式.

I would to like to write a script to find all specific words and format their color.

我尝试了以下操作,但似乎不起作用:

I tryied the following, but it seems it is not working:

function ChangeColor() {
  var body = DocumentApp.getActiveDocument().getBody();
  var myword = body.findText("var");

  while (myword !== null){
    var mysearch = myword.getElement().asText().setForegroundColor('#DC64DC');
  }
}

请问有人可以帮我吗?

推荐答案

您想要更改文档中"var"的字体颜色.如果我的理解是正确的,那么该修改如何?

You want to change the font color of "var" in the document. If my understanding is correct, how about this modification?

  • 为了搜索下一个单词,它使用findText(searchPattern, from).
  • 为了更改"var"的颜色,它使用setForegroundColor(startOffset, endOffsetInclusive, color).
    • 在脚本中,开始和结束的偏移量可以分别通过myword.getStartOffset()myword.getEndOffsetInclusive()检索.
    • In order to search next word, it uses findText(searchPattern, from).
    • In order to change the color of "var", it uses setForegroundColor(startOffset, endOffsetInclusive, color).
      • In your script, the offset of start and end can be retrieved by myword.getStartOffset() and myword.getEndOffsetInclusive(), respectively.
      function ChangeColor() {
        var searchValue = "var";
        var body = DocumentApp.getActiveDocument().getBody();
        var myword = body.findText(searchValue);
      
        while (myword) {
          var mysearch = myword.getElement().asText()
          mysearch.setForegroundColor(
            myword.getStartOffset(), // startOffset
            myword.getEndOffsetInclusive(), // endOffsetInclusive
            '#DC64DC' // color
          );
          var myword = body.findText(searchValue, myword); // Search next word
        }
      }
      

      参考文献:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆