获取用户选择的文本 [英] Get user-selected text
本文介绍了获取用户选择的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过鼠标在Google文档中选择 的单词或行,并通过脚本获取这些选定的单词或行.
I want to select words or lines by mouse in a Google Doc, and by script, get these selected words or lines.
示例:
var doc = DocumentApp.getActiveDocument();
var docText = doc.editAsText();
var text = docText.getSelection();
我尝试过,但是找不到像VBA那样的选择访问方法.
I tried, but I didn't find any methods for selection access like in VBA.
推荐答案
昨天添加了处理光标位置和所选文本的功能,地址为博客文章.
The ability to work with cursor position and selected text was added yesterday, addressing Issue 2865: Get current user location & state information in Document. See the blog post as well.
事实证明,使用选择有一些技巧.我已尝试在此处显示它们-如果您发现其他任何评论,请添加评论,我会很乐意更新.
It turns out that there are some tricks to working with selections. I've tried to show them here - please add comments if you find any others, I'll gladly update.
function onOpen() {
DocumentApp.getUi().createMenu('Selection')
.addItem("Report Selection", 'reportSelection' )
.addToUi();
}
function reportSelection () {
var doc = DocumentApp.getActiveDocument();
var selection = doc.getSelection();
var ui = DocumentApp.getUi();
var report = "Your Selection: ";
if (!selection) {
report += " No current selection ";
}
else {
var elements = selection.getSelectedElements();
// Report # elements. For simplicity, assume elements are paragraphs
report += " Paragraphs selected: " + elements.length + ". ";
if (elements.length > 1) {
}
else {
var element = elements[0].getElement();
var startOffset = elements[0].getStartOffset(); // -1 if whole element
var endOffset = elements[0].getEndOffsetInclusive(); // -1 if whole element
var selectedText = element.asText().getText(); // All text from element
// Is only part of the element selected?
if (elements[0].isPartial())
selectedText = selectedText.substring(startOffset,endOffset+1);
// Google Doc UI "word selection" (double click)
// selects trailing spaces - trim them
selectedText = selectedText.trim();
endOffset = startOffset + selectedText.length - 1;
// Now ready to hand off to format, setLinkUrl, etc.
report += " Selected text is: '" + selectedText + "', ";
report += " and is " + (elements[0].isPartial() ? "part" : "all") + " of the paragraph."
}
}
ui.alert( report );
}
这篇关于获取用户选择的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文