word - highlight search results without permanently changing document formatting

回眸只為那壹抹淺笑 提交于 2020-01-01 18:18:23

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!