![](/img/trans.png)
[英]Google apps script :: Is it possible to get the cursor position or get the selected text from Google Document
[英]Change the color of the word where the cursor is with Google Apps Script in a Google Document
我正在嘗試更改當前 google docs 光標所在的單詞的顏色(執行服務器功能時)。 我不知道該怎么做。 我看到: 在 google-apps-script 中獲取當前詞,它解釋了如何獲取該行的最后一個詞,但這並沒有真正起作用,這就是我所擁有的(非常粗略的代碼):
function clientize() {///
var t = Date.now();
var doc = DocumentApp.getActiveDocument().getCursor();
var els = doc.getElement();
var txt = els.asText().getText().split(" ");
var word = txt[txt.length - 1];
var offset = doc.getOffset();
var highlightStyle = {};
highlightStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#FF0000';
els.setBold(offset - 5,offset , true)
// els.setAttributes(4,10,highlightStyle);
return (word)
}
但它只給我行上的最后一個單詞,而不是光標實際所在的單詞,而且我不知道一旦找到文本,如何更改文檔中單詞的顏色。 我知道我可以根據特定范圍更改顏色,但它僅適用於 getElement(),但是如何更改光標所在的整個單詞的特定范圍?
例如,假設我有一行,帶有光標:
hello world ho|w are you today
然后當我激活服務器功能時,只有“如何”這個詞應該更改為紅色,例如。
這怎么可能????
您可以這樣做,訣竅是獲取當前用戶單詞開頭和結尾的偏移量。
function clientize() {
// Get the Position of the user's cursor
var position = DocumentApp.getActiveDocument().getCursor();
// Get the element that contains this Position
var ref_element = position.getElement();
// Get the text in the element
var text = ref_element.asText().getText();
// Get the cursor's relative location within ref_element.
// Verify if cursor is within text elem. or paragraph elem.
var ref_offset = position.getOffset();
if (ref_element.getType() == DocumentApp.ElementType.PARAGRAPH){
// Cursor is at beginning or end of line
if (ref_offset == 1){
// Cursor is at last word. Move to the left into TEXT
ref_offset = text.length - 1;
}
}
// Get offset for current word's initial char
var offset_first = ref_offset - text.substring(0,ref_offset).split(" ")[text.substring(0,ref_offset).split(" ").length - 1].length;
// Get how many chars to the end of current word
var chars_to_end;
if (text.substring(ref_offset, ref_offset + text.length - 1).indexOf(" ") > -1) {
// if word has a trailing space exclude it from count
chars_to_end = text.substring(ref_offset, ref_offset + text.length - 1).indexOf(" ");
} else {
chars_to_end = text.substring(ref_offset, ref_offset + text.length - 1).length - 1;
}
// Get offset for current word's last char
var offset_last = ref_offset + chars_to_end;
// Define the styling attributes
var style = {};
style[DocumentApp.Attribute.FOREGROUND_COLOR] = '#FF00FF';
// Apply styling to current word
ref_element.asText().setAttributes(offset_first, offset_last, style);
}
注意:如果返回的單詞后面或前面有逗號或其他字符,則必須過濾它。 提示:使用正則表達式。 看看這個帶有綁定腳本的測試文檔,看看它是否工作。
同樣供參考的關鍵函數是: setAttributes(startOffset, endOffsetInclusive, attributes)
請注意,有很多方法可以做到這一點,這只是實現它的一種方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.