问题
I would like to highlight the search results similarly to what word's native search is doing. In other words, I don't want the search action to have side effects in the document, e.g. by changing the color of the font in the returned text ranges.
var searchResults = paragraph.search(searchValue);
context.load(searchResults, { select: 'text, font, style' });
回答1:
right now the only way you can achieve your scenario is by traversing the search results collection and change the highlight color for each range like I am showing on the snippet below. To undo this operation you need to do the search again and restore the highlights to white.
Word.run(function (context) {
// Queue a command to search the document
var searchResults = context.document.body.search('string you want to search for');
context.load(searchResults, 'font');
return context.sync().then(function () {
console.log('Found count: ' + searchResults.items.length);
// Queue a set of commands to change the font for each found item.
for (var i = 0; i < searchResults.items.length; i++) {
searchResults.items[i].font.highlightColor = '#FFFF00'; //Yellow
}
return context.sync();
});
})
.catch(function (error) {
console.log('Error: ' + JSON.stringify(error));
if (error instanceof OfficeExtension.Error) {
console.log('Debug info: ' + JSON.stringify(error.debugInfo));
}
});
来源:https://stackoverflow.com/questions/40028375/word-highlight-search-results-without-permanently-changing-document-formatting