如何使用Office JavaScript API获取光标所在的Word.Section Range?
获取Word文档光标所在位置的Section范围
实现思路
要获取光标点击位置对应的Section范围,可通过Word JavaScript API实现:先定位当前光标所在的选区,再通过选区关联的正文对象找到所属的Section,最后获取该Section的文本范围。
代码示例
async function getCurrentSectionRange() { await Word.run(async (context) => { // 获取当前光标/选区对象 const selection = context.document.getSelection(); // 获取选区所属的Section const currentSection = selection.body.parentSection; // 加载Section的range属性(包含节的起始、结束位置等信息) currentSection.load('range'); // 同步执行API请求,获取数据 await context.sync(); // 输出Section范围的相关信息,可根据需求调整处理逻辑 console.log('当前Section的起始位置:', currentSection.range.start); console.log('当前Section的结束位置:', currentSection.range.end); console.log('当前Section的完整文本:', currentSection.range.text); }).catch((error) => { console.error('获取Section范围失败:', error); if (error instanceof OfficeExtension.Error) { console.error('详细错误信息:', error.debugInfo); } }); }
关键API说明(基于Word.Section类)
Section对象代表Word文档中的一个节,每个节可拥有独立的页面布局、页眉页脚等设置。- 通过内容对象(如选区、段落)的
parentSection属性,可向上追溯其所属的Section。 - Section的
range属性包含了该节的完整文本范围,可获取起始位置、结束位置、文本内容等核心信息,也可对该范围执行编辑、样式设置等操作。
内容的提问来源于stack exchange,提问作者user22905514
相关产品推荐
相关产品推荐

