我有以下情形Word:
font.color
,font.name
,font.size
等),这些内容是从内容选择中读取的控件被插入)问题在于,当内容控件更新时,当前文档的选择可以在任何地方,但是我需要确保它们重新应用与相邻文本相同的样式。
Office.js内是否有一种方法来获取与内容控件相邻的范围?这样,我就可以阅读它的样式并将其应用于内容控件。
答案 0 :(得分:1)
我的假设是,您希望文本紧接在内容控件之前。不幸的是,对象模型没有提供等效于a.map
的“后退”(getNextTextRange
)。
可以做到,但是有点麻烦。以下是我的脚本实验室示例代码:
getPreviousTextRange
在最后一个单词和内容控件之间有空格的情况下的代码:
async function
getAdjacentRange() {
await Word.run(async (context) => {
var ccs = context.document.contentControls;
ccs.load("items");
await context.sync();
console.log("Nr cc: " + ccs.items.length);
let cc = ccs.items[0];
//The starting point of the content control so that
//the range can be extended backwards
let ccRange = cc.getRange("Start");
let ccParas = ccRange.paragraphs; cc.load("text,range,paragraphs");
let ccPara = ccParas.getFirst();
ccParas.load("items")
//The content control must be in a paragraph: get that paragraph's
//starting point so that the range can be extended in that direction
let paraRange = ccPara.getRange("Start");
let rng = paraRange.expandTo(ccRange);
//Get the words in the range of the start of the paragraph to the
//start of the content control in order to get the last one before the content control
let em = [" "];
let words = rng.getTextRanges(em, true);
words.load("items");
await context.sync();
let nrWords = words.items.length;
//minus 2 to get second to last word since last word is directly adjacent to content control (no space)
let lastWord = words.items[nrWords - 2];
//Now get the content from the end of the second to last word to
//the start of the content control, which will be the last word
let word2BeforeCC = lastWord.getRange("End");
let wordBeforeCC = word2BeforeCC.expandTo(ccRange);
wordBeforeCC.load("text");
await context.sync();
console.log(cc.text + "/ Word before the content control: " + wordBeforeCC.text + " / nr Words: " + nrWords);
})
}