我有一个带有一些文字的Google文档,我创建了一个补充工具栏。我想要的是当有人突出显示一个单词时,然后使用侧边栏中的单选按钮单击一个选项,该单词将根据所选的选项以颜色突出显示。 我已经使用HtmlService获得了带有单选按钮的侧边栏,并且我有一些Google Apps脚本会突出显示该单词。 我正在努力的是找到一种方法来注册哪个单选按钮,然后可以用它来决定选择哪种颜色。 我已设法在HTML代码中使用Javascript触发操作,但我无法将其与突出显示该单词的函数链接。我一直试图在选择按钮时设置一个变量,然后可以在If语句中使用它来决定要添加的颜色。 这是我到目前为止编写的GAS代码和HTML。 如果有人对什么缺失有任何想法,他们将不胜感激。 谢谢!
//Function to create sidebar and get HTML from file called Index
function sidebar() {
var htmlOutput = HtmlService.createHtmlOutputFromFile('Index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle('Writing codes');
DocumentApp.getUi().showSidebar(htmlOutput);
}
以下是文件“Index.html”
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<p>Highlight an area and click on a code below to highlight it in the text.</p>
<form>
<input type="radio" name="error" id="GrammarBut"/> Grammar<br />
<input type="radio" name="error" id="VocabBut"/> Vocabulary<br />
<input type="radio" name="error" id="WOBut"/> Word order<br />
<br />
<div class="block">
<button class="blue">Add</button>
</div>
</form>
</body>
</html>
下面是功能highlightText,用于突出显示该单词。
function highlightText() {
var selection = DocumentApp.getActiveDocument().getSelection();
if (selection) {
var elements = selection.getRangeElements();
for (var i = 0; i < elements.length; i++) {
var element2 = elements[i];
// Only modify elements that can be edited as text; skip images and other non-text elements.
if (element2.getElement().editAsText) {
var text = element2.getElement().editAsText();
if (element2.isPartial()) {
text.setBackgroundColor(element2.getStartOffset(), element2.getEndOffsetInclusive(), "#FFFD4C");
} else {
text.setBackgroundColor("#FFFD4C");
}
}
}
}
}
答案 0 :(得分:2)
添加一个触发客户端JavaScript函数的onclick事件,并引用触发元素。然后用您的颜色选择调用服务器端功能。
单选按钮元素:
<form>
<input onclick="chngColor(this)" type="radio" name="error" id="GrammarBut"/> Grammar<br />
<input onclick="chngColor(this)" type="radio" name="error" id="VocabBut"/> Vocabulary<br />
<input onclick="chngColor(this)" type="radio" name="error" id="WOBut"/> Word order<br />
<br />
客户端JavaScript:
function chngColor(element)
{
var id = element.id;
var color;
if(id == "GrammerBut")
color = "the color you need";
else if(id == "VocabBut")
color = "next color";
else if(id == "WOBut")
color = "final color";
google.script.run.highlightText(color);
}
然后只需更改服务器端功能以接受参数来设置颜色,或者您需要做的其他事情。