Word.ContentControl class

表示内容控件。 内容控件是文档中绑定的、有可能添加标签的区域,它们充当特定类型的内容的容器。 各个内容控件可能包含诸如图像、表格或格式化文本段落等内容。 目前,仅支持格式文本、纯文本和复选框内容控件。

Extends

注解

[ API 集:WordApi 1.1 ]

示例

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;

    // Queue a command to load the id property for all of the content controls.
    contentControls.load('id');

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to load the properties on the first content control.
        contentControls.items[0].load(  'appearance,' +
                                        'cannotDelete,' +
                                        'cannotEdit,' +
                                        'color,' +
                                        'id,' +
                                        'placeHolderText,' +
                                        'removeWhenEdited,' +
                                        'title,' +
                                        'text,' +
                                        'type,' +
                                        'style,' +
                                        'tag,' +
                                        'font/size,' +
                                        'font/name,' +
                                        'font/color');

        // Synchronize the document state by executing the queued commands,
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Property values of the first content control:' +
            '   ----- appearance: ' + contentControls.items[0].appearance +
            '   ----- cannotDelete: ' + contentControls.items[0].cannotDelete +
            '   ----- cannotEdit: ' + contentControls.items[0].cannotEdit +
            '   ----- color: ' + contentControls.items[0].color +
            '   ----- id: ' + contentControls.items[0].id +
            '   ----- placeHolderText: ' + contentControls.items[0].placeholderText +
            '   ----- removeWhenEdited: ' + contentControls.items[0].removeWhenEdited +
            '   ----- title: ' + contentControls.items[0].title +
            '   ----- text: ' + contentControls.items[0].text +
            '   ----- type: ' + contentControls.items[0].type +
            '   ----- style: ' + contentControls.items[0].style +
            '   ----- tag: ' + contentControls.items[0].tag +
            '   ----- font size: ' + contentControls.items[0].font.size +
            '   ----- font name: ' + contentControls.items[0].font.name +
            '   ----- font color: ' + contentControls.items[0].font.color);
    }
});

属性

appearance

指定内容控件的外观。 该值可以是“BoundingBox”、“Tags”或“Hidden”。

cannotDelete

指定一个值,该值指示用户是否可以删除内容控件。 与 removeWhenEdited 互相排斥。

cannotEdit

指定一个值,该值指示用户是否可以编辑内容控件的内容。

checkboxContentControl

如果内容控件的类型为“CheckBox”,则指定与复选框相关的数据。 否则为 null。

color

指定内容控件的颜色。 颜色以“#RRGGBB”格式或使用颜色名称指定。

contentControls

获取内容控件中的内容控件对象的集合。

context

与 对象关联的请求上下文。 这会将加载项的进程连接到 Office 主机应用程序的进程。

dropDownListContentControl

如果内容控件的类型为“DropDownList”,则指定与下拉列表相关的数据。 否则为 null。

endnotes

获取内容控件中尾注的集合。

fields

获取内容控件中字段对象的集合。

font

获取内容控件的文本格式。 使用此对象获取和设置字体名称、大小、颜色和其他属性。

footnotes

获取内容控件中的脚注集合。

id

获取表示内容控件标识符的整数。

inlinePictures

获取内容控件中 InlinePicture 对象的集合。 集合不包括浮动图像。

lists

获取 contentControl 中的一组 list 对象。

paragraphs

获取内容控件中段落对象的集合。

parentBody

获取 contentControl 的父正文。

parentContentControl

获取包含此内容控件的内容控件。 ItemNotFound如果没有父内容控件,则引发错误。

parentContentControlOrNullObject

获取包含此内容控件的内容控件。 如果没有父内容控件,则此方法将返回其属性设置为 true的对象isNullObject。 有关详细信息,请参阅 *OrNullObject 方法和属性

parentTable

获取包含 contentControl 的 table。 ItemNotFound如果未包含在表中,则引发错误。

parentTableCell

获取包含 contentControl 的 tableCell。 ItemNotFound如果表单元格中未包含错误,则引发错误。

parentTableCellOrNullObject

获取包含 contentControl 的 tableCell。 如果它未包含在表单元格中,则此方法将返回其 isNullObject 属性设置为 true的对象。 有关详细信息,请参阅 *OrNullObject 方法和属性

parentTableOrNullObject

获取包含 contentControl 的 table。 如果它未包含在表中,则此方法将返回一个 对象,其 isNullObject 属性设置为 true。 有关详细信息,请参阅 *OrNullObject 方法和属性

placeholderText

指定内容控件的占位符文本。 内容控件为空时,将显示灰色的文本。

注意:web 上的Word不支持此属性的设置操作。

removeWhenEdited

指定一个值,该值指示内容控件在编辑后是否将其删除。 与 cannotDelete 互相排斥。

style

指定内容控件的样式名称。 请对自定义样式和本地化样式名称使用此属性。 若要使用可以在区域设置之间移植的嵌入样式,请参阅“styleBuiltIn”属性。

styleBuiltIn

指定内容控件的内置样式名称。 请对可以在区域设置之间移植的嵌入样式使用此属性。 若要使用自定义样式或本地化样式名称,请参阅“style”属性。

subtype

获取 contentControl 的子类型。 对于富文本内容控件,子类型可以是“RichTextInline”、“RichTextParagraphs”、“RichTextTableCell”、“RichTextTableRow”和“RichTextTable”,或者对于纯文本内容控件,可以是“PlainTextInline”和“PlainTextParagraph”,也可以是复选框内容控件的“CheckBox”。

tables

获取 contentControl 中的一组 table 对象。

tag

指定用于标识内容控件的标记。

text

获取内容控件的文本。

title

指定内容控件的标题。

type

获取内容控件的类型。 目前仅支持格式文本、纯文本和复选框内容控件。

方法

clear()

清除内容控件的内容。 用户可以对已清除的内容执行撤消操作。

delete(keepContent)

删除内容控件及其内容。 如果 keepContent 设置为 true,则不会删除内容。

getComments()

获取与内容控件关联的注释。

getContentControls(options)

获取此内容控件中当前支持的子内容控件。

getHtml()

获取内容控件对象的 HTML 表示形式。 在网页或 HTML 查看器中呈现时,格式将与文档的格式相匹配,但不完全匹配。 此方法不会为不同平台上的相同文档返回完全相同的 HTML, (Windows、Mac、web 上的Word等 ) 。 如果需要精确保真度或跨平台的一致性,请使用 ContentControl.getOoxml() 返回的 XML 并将其转换为 HTML。

getOoxml()

获取内容控件对象的 Office Open XML (OOXML) 表示形式。

getRange(rangeLocation)

获取整个内容控件或内容控件的起点/终点,作为一个范围。

getReviewedText(changeTrackingVersion)

根据 ChangeTrackingVersion 选择获取审阅的文本。

getReviewedText(changeTrackingVersionString)

根据 ChangeTrackingVersion 选择获取审阅的文本。

getTextRanges(endingMarks, trimSpacing)

使用标点符号和/或其他结束标记获取内容控件中的文本范围。

getTrackedChanges()

获取内容控件中 TrackedChange 对象的集合。

insertBreak(breakType, insertLocation)

在主文档的指定位置插入分隔符。 此方法不能与“RichTextTable”、“RichTextTableRow”和“RichTextTableCell”内容控件一起使用。

insertFileFromBase64(base64File, insertLocation)

将文档插入到位于指定位置的内容控件中。

insertHtml(html, insertLocation)

将 HTML 插入到内容控件中的指定位置。

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

将嵌入式图片插入到内容控件中的指定位置。

insertOoxml(ooxml, insertLocation)

将 OOXML 插入到指定位置的内容控件中。

insertParagraph(paragraphText, insertLocation)

在指定位置插入段落。

insertTable(rowCount, columnCount, insertLocation, values)

将包含指定行数和列数的 table 插入 contentControl 中或在其旁边插入。

insertText(text, insertLocation)

将文本插入到内容控件中的指定位置。

load(options)

将命令加入队列以加载对象的指定属性。 阅读属性前必须先调用 context.sync()

load(propertyNames)

将命令加入队列以加载对象的指定属性。 阅读属性前必须先调用 context.sync()

load(propertyNamesAndPaths)

将命令加入队列以加载对象的指定属性。 阅读属性前必须先调用 context.sync()

resetState()

重置内容控件的状态。

search(searchText, searchOptions)

对内容控件对象的作用域使用指定的 SearchOptions 执行搜索。 搜索结果是 range 对象的集合。

select(selectionMode)

选择内容控件。 这会导致 Word 滚动到选定内容。

select(selectionModeString)

选择内容控件。 这会导致 Word 滚动到选定内容。

set(properties, options)

同时设置对象的多个属性。 可以传递具有相应属性的纯对象,也可以传递同一类型的另一个 API 对象。

set(properties)

基于现有的已加载对象,同时对对象设置多个属性。

setState(contentControlState)

设置内容控件的状态。

setState(contentControlStateString)

设置内容控件的状态。

split(delimiters, multiParagraphs, trimDelimiters, trimSpacing)

使用分隔符将内容控件拆分为各个子范围。

toJSON()

重写 JavaScript toJSON() 方法,以便在将 API 对象传递给 JSON.stringify()时提供更有用的输出。 JSON.stringify (,反过来又调用toJSON传递给它的 对象的 方法。) 而原始Word。ContentControl 对象是一个 API 对象,toJSON该方法返回一个纯 JavaScript 对象, (类型为 Word.Interfaces.ContentControlData) ,其中包含原始对象中任何已加载子属性的浅表副本。

track()

根据文档中的相应更改来跟踪对象,以便进行自动调整。 此调用是 context.trackedObjects.add (thisObject) 的简写。 如果跨 .sync 调用和“.run”批处理的顺序执行外部使用此对象,并在设置属性或调用对象方法时收到“InvalidObjectPath”错误,则需要在首次创建对象时将该对象添加到跟踪的对象集合。 如果此对象是集合的一部分,则还应跟踪父集合。

untrack()

释放与此对象关联的内存(如果先前已跟踪过)。 此调用是 context.trackedObjects.remove (thisObject) 的简写。 拥有许多跟踪对象会降低主机应用程序的速度,因此请在使用完毕后释放所添加的任何对象。 在内存发布生效之前,需要调用 context.sync()

事件

onCommentAdded

在添加新注释时发生。

onCommentChanged

更改批注或其回复时发生。

onCommentDeselected

在取消选择批注时发生。

onCommentSelected

在选择批注时发生。

onDataChanged

在更改内容控件中的数据时发生。 若要获取新文本,请在处理程序中加载此内容控件。 若要获取旧文本,请不要加载它。

onDeleted

删除内容控件时发生。 请勿在处理程序中加载此内容控件,否则将无法获取其原始属性。

onEntered

在输入内容控件时发生。

onExited

在退出内容控件时发生,例如,当光标离开内容控件时。

onSelectionChanged

更改内容控件中的选择时发生。

属性详细信息

appearance

指定内容控件的外观。 该值可以是“BoundingBox”、“Tags”或“Hidden”。

appearance: Word.ContentControlAppearance | "BoundingBox" | "Tags" | "Hidden";

属性值

Word.ContentControlAppearance | "BoundingBox" | "Tags" | "Hidden"

注解

[ API 集:WordApi 1.1 ]

cannotDelete

指定一个值,该值指示用户是否可以删除内容控件。 与 removeWhenEdited 互相排斥。

cannotDelete: boolean;

属性值

boolean

注解

[ API 集:WordApi 1.1 ]

cannotEdit

指定一个值,该值指示用户是否可以编辑内容控件的内容。

cannotEdit: boolean;

属性值

boolean

注解

[ API 集:WordApi 1.1 ]

checkboxContentControl

如果内容控件的类型为“CheckBox”,则指定与复选框相关的数据。 否则为 null。

readonly checkboxContentControl: Word.CheckboxContentControl;

属性值

注解

[ API 集:WordApi 1.7 ]

color

指定内容控件的颜色。 颜色以“#RRGGBB”格式或使用颜色名称指定。

color: string;

属性值

string

注解

[ API 集:WordApi 1.1 ]

contentControls

获取内容控件中的内容控件对象的集合。

readonly contentControls: Word.ContentControlCollection;

属性值

注解

[ API 集:WordApi 1.1 ]

context

与 对象关联的请求上下文。 这会将加载项的进程连接到 Office 主机应用程序的进程。

context: RequestContext;

属性值

dropDownListContentControl

注意

此 API 以预览状态提供给开发者,可能根据我们收到的反馈更改。 请勿在生产环境中使用此 API。

如果内容控件的类型为“DropDownList”,则指定与下拉列表相关的数据。 否则为 null。

readonly dropDownListContentControl: Word.DropDownListContentControl;

属性值

注解

[ API 集:WordApi BETA (仅预览版) ]

endnotes

获取内容控件中尾注的集合。

readonly endnotes: Word.NoteItemCollection;

属性值

注解

[ API 集:WordApi 1.5 ]

fields

获取内容控件中字段对象的集合。

readonly fields: Word.FieldCollection;

属性值

注解

[ API 集:WordApi 1.4 ]

font

获取内容控件的文本格式。 使用此对象获取和设置字体名称、大小、颜色和其他属性。

readonly font: Word.Font;

属性值

注解

[ API 集:WordApi 1.1 ]

footnotes

获取内容控件中的脚注集合。

readonly footnotes: Word.NoteItemCollection;

属性值

注解

[ API 集:WordApi 1.5 ]

id

获取表示内容控件标识符的整数。

readonly id: number;

属性值

number

注解

[ API 集:WordApi 1.1 ]

inlinePictures

获取内容控件中 InlinePicture 对象的集合。 集合不包括浮动图像。

readonly inlinePictures: Word.InlinePictureCollection;

属性值

注解

[ API 集:WordApi 1.1 ]

lists

获取 contentControl 中的一组 list 对象。

readonly lists: Word.ListCollection;

属性值

注解

[ API 集:WordApi 1.3 ]

paragraphs

获取内容控件中段落对象的集合。

readonly paragraphs: Word.ParagraphCollection;

属性值

注解

[ API 集:WordApi 1.1 ]

重要提示:对于要求集 1.1 和 1.2,不会返回完全包含在此内容控件中的表中的段落。 从要求集 1.3 中,还会返回此类表中的段落。

parentBody

获取 contentControl 的父正文。

readonly parentBody: Word.Body;

属性值

注解

[ API 集:WordApi 1.3 ]

parentContentControl

获取包含此内容控件的内容控件。 ItemNotFound如果没有父内容控件,则引发错误。

readonly parentContentControl: Word.ContentControl;

属性值

注解

[ API 集:WordApi 1.1 ]

parentContentControlOrNullObject

获取包含此内容控件的内容控件。 如果没有父内容控件,则此方法将返回其属性设置为 true的对象isNullObject。 有关详细信息,请参阅 *OrNullObject 方法和属性

readonly parentContentControlOrNullObject: Word.ContentControl;

属性值

注解

[ API 集:WordApi 1.3 ]

parentTable

获取包含 contentControl 的 table。 ItemNotFound如果未包含在表中,则引发错误。

readonly parentTable: Word.Table;

属性值

注解

[ API 集:WordApi 1.3 ]

parentTableCell

获取包含 contentControl 的 tableCell。 ItemNotFound如果表单元格中未包含错误,则引发错误。

readonly parentTableCell: Word.TableCell;

属性值

注解

[ API 集:WordApi 1.3 ]

parentTableCellOrNullObject

获取包含 contentControl 的 tableCell。 如果它未包含在表单元格中,则此方法将返回其 isNullObject 属性设置为 true的对象。 有关详细信息,请参阅 *OrNullObject 方法和属性

readonly parentTableCellOrNullObject: Word.TableCell;

属性值

注解

[ API 集:WordApi 1.3 ]

parentTableOrNullObject

获取包含 contentControl 的 table。 如果它未包含在表中,则此方法将返回一个 对象,其 isNullObject 属性设置为 true。 有关详细信息,请参阅 *OrNullObject 方法和属性

readonly parentTableOrNullObject: Word.Table;

属性值

注解

[ API 集:WordApi 1.3 ]

placeholderText

指定内容控件的占位符文本。 内容控件为空时,将显示灰色的文本。

注意:web 上的Word不支持此属性的设置操作。

placeholderText: string;

属性值

string

注解

[ API 集:WordApi 1.1 ]

removeWhenEdited

指定一个值,该值指示内容控件在编辑后是否将其删除。 与 cannotDelete 互相排斥。

removeWhenEdited: boolean;

属性值

boolean

注解

[ API 集:WordApi 1.1 ]

style

指定内容控件的样式名称。 请对自定义样式和本地化样式名称使用此属性。 若要使用可以在区域设置之间移植的嵌入样式,请参阅“styleBuiltIn”属性。

style: string;

属性值

string

注解

[ API 集:WordApi 1.1 ]

styleBuiltIn

指定内容控件的内置样式名称。 请对可以在区域设置之间移植的嵌入样式使用此属性。 若要使用自定义样式或本地化样式名称,请参阅“style”属性。

styleBuiltIn: Word.BuiltInStyleName | "Other" | "Normal" | "Heading1" | "Heading2" | "Heading3" | "Heading4" | "Heading5" | "Heading6" | "Heading7" | "Heading8" | "Heading9" | "Toc1" | "Toc2" | "Toc3" | "Toc4" | "Toc5" | "Toc6" | "Toc7" | "Toc8" | "Toc9" | "FootnoteText" | "Header" | "Footer" | "Caption" | "FootnoteReference" | "EndnoteReference" | "EndnoteText" | "Title" | "Subtitle" | "Hyperlink" | "Strong" | "Emphasis" | "NoSpacing" | "ListParagraph" | "Quote" | "IntenseQuote" | "SubtleEmphasis" | "IntenseEmphasis" | "SubtleReference" | "IntenseReference" | "BookTitle" | "Bibliography" | "TocHeading" | "TableGrid" | "PlainTable1" | "PlainTable2" | "PlainTable3" | "PlainTable4" | "PlainTable5" | "TableGridLight" | "GridTable1Light" | "GridTable1Light_Accent1" | "GridTable1Light_Accent2" | "GridTable1Light_Accent3" | "GridTable1Light_Accent4" | "GridTable1Light_Accent5" | "GridTable1Light_Accent6" | "GridTable2" | "GridTable2_Accent1" | "GridTable2_Accent2" | "GridTable2_Accent3" | "GridTable2_Accent4" | "GridTable2_Accent5" | "GridTable2_Accent6" | "GridTable3" | "GridTable3_Accent1" | "GridTable3_Accent2" | "GridTable3_Accent3" | "GridTable3_Accent4" | "GridTable3_Accent5" | "GridTable3_Accent6" | "GridTable4" | "GridTable4_Accent1" | "GridTable4_Accent2" | "GridTable4_Accent3" | "GridTable4_Accent4" | "GridTable4_Accent5" | "GridTable4_Accent6" | "GridTable5Dark" | "GridTable5Dark_Accent1" | "GridTable5Dark_Accent2" | "GridTable5Dark_Accent3" | "GridTable5Dark_Accent4" | "GridTable5Dark_Accent5" | "GridTable5Dark_Accent6" | "GridTable6Colorful" | "GridTable6Colorful_Accent1" | "GridTable6Colorful_Accent2" | "GridTable6Colorful_Accent3" | "GridTable6Colorful_Accent4" | "GridTable6Colorful_Accent5" | "GridTable6Colorful_Accent6" | "GridTable7Colorful" | "GridTable7Colorful_Accent1" | "GridTable7Colorful_Accent2" | "GridTable7Colorful_Accent3" | "GridTable7Colorful_Accent4" | "GridTable7Colorful_Accent5" | "GridTable7Colorful_Accent6" | "ListTable1Light" | "ListTable1Light_Accent1" | "ListTable1Light_Accent2" | "ListTable1Light_Accent3" | "ListTable1Light_Accent4" | "ListTable1Light_Accent5" | "ListTable1Light_Accent6" | "ListTable2" | "ListTable2_Accent1" | "ListTable2_Accent2" | "ListTable2_Accent3" | "ListTable2_Accent4" | "ListTable2_Accent5" | "ListTable2_Accent6" | "ListTable3" | "ListTable3_Accent1" | "ListTable3_Accent2" | "ListTable3_Accent3" | "ListTable3_Accent4" | "ListTable3_Accent5" | "ListTable3_Accent6" | "ListTable4" | "ListTable4_Accent1" | "ListTable4_Accent2" | "ListTable4_Accent3" | "ListTable4_Accent4" | "ListTable4_Accent5" | "ListTable4_Accent6" | "ListTable5Dark" | "ListTable5Dark_Accent1" | "ListTable5Dark_Accent2" | "ListTable5Dark_Accent3" | "ListTable5Dark_Accent4" | "ListTable5Dark_Accent5" | "ListTable5Dark_Accent6" | "ListTable6Colorful" | "ListTable6Colorful_Accent1" | "ListTable6Colorful_Accent2" | "ListTable6Colorful_Accent3" | "ListTable6Colorful_Accent4" | "ListTable6Colorful_Accent5" | "ListTable6Colorful_Accent6" | "ListTable7Colorful" | "ListTable7Colorful_Accent1" | "ListTable7Colorful_Accent2" | "ListTable7Colorful_Accent3" | "ListTable7Colorful_Accent4" | "ListTable7Colorful_Accent5" | "ListTable7Colorful_Accent6";

属性值

Word.BuiltInStyleName | "Other" | "Normal" | "Heading1" | "Heading2" | "Heading3" | "Heading4" | "Heading5" | "Heading6" | "Heading7" | "Heading8" | "Heading9" | "Toc1" | "Toc2" | "Toc3" | "Toc4" | "Toc5" | "Toc6" | "Toc7" | "Toc8" | "Toc9" | "FootnoteText" | "Header" | "Footer" | "Caption" | "FootnoteReference" | "EndnoteReference" | "EndnoteText" | "Title" | "Subtitle" | "Hyperlink" | "Strong" | "Emphasis" | "NoSpacing" | "ListParagraph" | "Quote" | "IntenseQuote" | "SubtleEmphasis" | "IntenseEmphasis" | "SubtleReference" | "IntenseReference" | "BookTitle" | "Bibliography" | "TocHeading" | "TableGrid" | "PlainTable1" | "PlainTable2" | "PlainTable3" | "PlainTable4" | "PlainTable5" | "TableGridLight" | "GridTable1Light" | "GridTable1Light_Accent1" | "GridTable1Light_Accent2" | "GridTable1Light_Accent3" | "GridTable1Light_Accent4" | "GridTable1Light_Accent5" | "GridTable1Light_Accent6" | "GridTable2" | "GridTable2_Accent1" | "GridTable2_Accent2" | "GridTable2_Accent3" | "GridTable2_Accent4" | "GridTable2_Accent5" | "GridTable2_Accent6" | "GridTable3" | "GridTable3_Accent1" | "GridTable3_Accent2" | "GridTable3_Accent3" | "GridTable3_Accent4" | "GridTable3_Accent5" | "GridTable3_Accent6" | "GridTable4" | "GridTable4_Accent1" | "GridTable4_Accent2" | "GridTable4_Accent3" | "GridTable4_Accent4" | "GridTable4_Accent5" | "GridTable4_Accent6" | "GridTable5Dark" | "GridTable5Dark_Accent1" | "GridTable5Dark_Accent2" | "GridTable5Dark_Accent3" | "GridTable5Dark_Accent4" | "GridTable5Dark_Accent5" | "GridTable5Dark_Accent6" | "GridTable6Colorful" | "GridTable6Colorful_Accent1" | "GridTable6Colorful_Accent2" | "GridTable6Colorful_Accent3" | "GridTable6Colorful_Accent4" | "GridTable6Colorful_Accent5" | "GridTable6Colorful_Accent6" | "GridTable7Colorful" | "GridTable7Colorful_Accent1" | "GridTable7Colorful_Accent2" | "GridTable7Colorful_Accent3" | "GridTable7Colorful_Accent4" | "GridTable7Colorful_Accent5" | "GridTable7Colorful_Accent6" | "ListTable1Light" | "ListTable1Light_Accent1" | "ListTable1Light_Accent2" | "ListTable1Light_Accent3" | "ListTable1Light_Accent4" | "ListTable1Light_Accent5" | "ListTable1Light_Accent6" | "ListTable2" | "ListTable2_Accent1" | "ListTable2_Accent2" | "ListTable2_Accent3" | "ListTable2_Accent4" | "ListTable2_Accent5" | "ListTable2_Accent6" | "ListTable3" | "ListTable3_Accent1" | "ListTable3_Accent2" | "ListTable3_Accent3" | "ListTable3_Accent4" | "ListTable3_Accent5" | "ListTable3_Accent6" | "ListTable4" | "ListTable4_Accent1" | "ListTable4_Accent2" | "ListTable4_Accent3" | "ListTable4_Accent4" | "ListTable4_Accent5" | "ListTable4_Accent6" | "ListTable5Dark" | "ListTable5Dark_Accent1" | "ListTable5Dark_Accent2" | "ListTable5Dark_Accent3" | "ListTable5Dark_Accent4" | "ListTable5Dark_Accent5" | "ListTable5Dark_Accent6" | "ListTable6Colorful" | "ListTable6Colorful_Accent1" | "ListTable6Colorful_Accent2" | "ListTable6Colorful_Accent3" | "ListTable6Colorful_Accent4" | "ListTable6Colorful_Accent5" | "ListTable6Colorful_Accent6" | "ListTable7Colorful" | "ListTable7Colorful_Accent1" | "ListTable7Colorful_Accent2" | "ListTable7Colorful_Accent3" | "ListTable7Colorful_Accent4" | "ListTable7Colorful_Accent5" | "ListTable7Colorful_Accent6"

注解

[ API 集:WordApi 1.3 ]

subtype

获取 contentControl 的子类型。 对于富文本内容控件,子类型可以是“RichTextInline”、“RichTextParagraphs”、“RichTextTableCell”、“RichTextTableRow”和“RichTextTable”,或者对于纯文本内容控件,可以是“PlainTextInline”和“PlainTextParagraph”,也可以是复选框内容控件的“CheckBox”。

readonly subtype: Word.ContentControlType | "Unknown" | "RichTextInline" | "RichTextParagraphs" | "RichTextTableCell" | "RichTextTableRow" | "RichTextTable" | "PlainTextInline" | "PlainTextParagraph" | "Picture" | "BuildingBlockGallery" | "CheckBox" | "ComboBox" | "DropDownList" | "DatePicker" | "RepeatingSection" | "RichText" | "PlainText";

属性值

Word.ContentControlType | "Unknown" | "RichTextInline" | "RichTextParagraphs" | "RichTextTableCell" | "RichTextTableRow" | "RichTextTable" | "PlainTextInline" | "PlainTextParagraph" | "Picture" | "BuildingBlockGallery" | "CheckBox" | "ComboBox" | "DropDownList" | "DatePicker" | "RepeatingSection" | "RichText" | "PlainText"

注解

[ API 集:WordApi 1.3 ]

tables

获取 contentControl 中的一组 table 对象。

readonly tables: Word.TableCollection;

属性值

注解

[ API 集:WordApi 1.3 ]

tag

指定用于标识内容控件的标记。

tag: string;

属性值

string

注解

[ API 集:WordApi 1.1 ]

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/insert-and-change-content-controls.yaml

// Traverses each paragraph of the document and wraps a content control on each with either a even or odd tags.
await Word.run(async (context) => {
  let paragraphs = context.document.body.paragraphs;
  paragraphs.load("$none"); // Don't need any properties; just wrap each paragraph with a content control.

  await context.sync();

  for (let i = 0; i < paragraphs.items.length; i++) {
    let contentControl = paragraphs.items[i].insertContentControl();
    // For even, tag "even".
    if (i % 2 === 0) {
      contentControl.tag = "even";
    } else {
      contentControl.tag = "odd";
    }
  }
  console.log("Content controls inserted: " + paragraphs.items.length);

  await context.sync();
});

text

获取内容控件的文本。

readonly text: string;

属性值

string

注解

[ API 集:WordApi 1.1 ]

title

指定内容控件的标题。

title: string;

属性值

string

注解

[ API 集:WordApi 1.1 ]

type

获取内容控件的类型。 目前仅支持格式文本、纯文本和复选框内容控件。

readonly type: Word.ContentControlType | "Unknown" | "RichTextInline" | "RichTextParagraphs" | "RichTextTableCell" | "RichTextTableRow" | "RichTextTable" | "PlainTextInline" | "PlainTextParagraph" | "Picture" | "BuildingBlockGallery" | "CheckBox" | "ComboBox" | "DropDownList" | "DatePicker" | "RepeatingSection" | "RichText" | "PlainText";

属性值

Word.ContentControlType | "Unknown" | "RichTextInline" | "RichTextParagraphs" | "RichTextTableCell" | "RichTextTableRow" | "RichTextTable" | "PlainTextInline" | "PlainTextParagraph" | "Picture" | "BuildingBlockGallery" | "CheckBox" | "ComboBox" | "DropDownList" | "DatePicker" | "RepeatingSection" | "RichText" | "PlainText"

注解

[ API 集:WordApi 1.1 ]

方法详细信息

clear()

清除内容控件的内容。 用户可以对已清除的内容执行撤消操作。

clear(): void;

返回

void

注解

[ API 集:WordApi 1.1 ]

示例

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the content controls collection.
    contentControls.load('text');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
        
    if (contentControls.items.length === 0) {
        console.log("There isn't a content control in this document.");
    } else {
        // Queue a command to clear the contents of the first content control.
        contentControls.items[0].clear();

        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Content control cleared of contents.');
    }
});

delete(keepContent)

删除内容控件及其内容。 如果 keepContent 设置为 true,则不会删除内容。

delete(keepContent: boolean): void;

参数

keepContent

boolean

必填。 指示是否应使用内容控件删除内容。 如果 keepContent 设置为 true,则不会删除内容。

返回

void

注解

[ API 集:WordApi 1.1 ]

示例

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the content controls collection.
    contentControls.load('text');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
        
    if (contentControls.items.length === 0) {
        console.log("There isn't a content control in this document.");
    } else {            
        // Queue a command to delete the first content control. 
        // The contents will remain in the document.
        contentControls.items[0].delete(true);

        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Content control cleared of contents.'); 
    }
});
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/content-control-ondeleted-event.yaml

await Word.run(async (context) => {
  const contentControls = context.document.contentControls.getByTag("forTesting");
  contentControls.load("items");
  await context.sync();

  if (contentControls.items.length === 0) {
    console.log("There are no content controls in this document.");
  } else {
    console.log("Control to be deleted:");
    console.log(contentControls.items[0]);
    contentControls.items[0].delete(false);
    await context.sync();
  }
});

getComments()

获取与内容控件关联的注释。

getComments(): Word.CommentCollection;

返回

注解

[ API 集:WordApi 1.4 ]

getContentControls(options)

获取此内容控件中当前支持的子内容控件。

getContentControls(options?: Word.ContentControlOptions): Word.ContentControlCollection;

参数

options
Word.ContentControlOptions

可选。 用于定义返回哪些内容控件的选项。

返回

注解

[ API 集:WordApi 1.5 ]

重要说明:如果在 options 参数中提供了特定类型,则仅返回受支持类型的内容控件。 请注意,在使用泛型Word的方法时将引发异常与特定类型无关的 ContentControl。 随着时间的推移,可能会支持其他类型的内容控件。 因此,外接程序应请求并处理特定类型的内容控件。

getHtml()

获取内容控件对象的 HTML 表示形式。 在网页或 HTML 查看器中呈现时,格式将与文档的格式相匹配,但不完全匹配。 此方法不会为不同平台上的相同文档返回完全相同的 HTML, (Windows、Mac、web 上的Word等 ) 。 如果需要精确保真度或跨平台的一致性,请使用 ContentControl.getOoxml() 返回的 XML 并将其转换为 HTML。

getHtml(): OfficeExtension.ClientResult<string>;

返回

注解

[ API 集:WordApi 1.1 ]

示例

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection that contains a specific tag.
    const contentControlsWithTag = context.document.contentControls.getByTag('Customer-Address');
    
    // Queue a command to load the tag property for all of content controls.
    contentControlsWithTag.load('tag');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControlsWithTag.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to get the HTML contents of the first content control.
        const html = contentControlsWithTag.items[0].getHtml();
    
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Content control HTML: ' + html.value);
    }
});

getOoxml()

获取内容控件对象的 Office Open XML (OOXML) 表示形式。

getOoxml(): OfficeExtension.ClientResult<string>;

返回

注解

[ API 集:WordApi 1.1 ]

示例

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the id property for all of the content controls.
    contentControls.load('id');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to get the OOXML contents of the first content control.
        const ooxml = contentControls.items[0].getOoxml();
    
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Content control OOXML: ' + ooxml.value);
    }
});

getRange(rangeLocation)

获取整个内容控件或内容控件的起点/终点,作为一个范围。

getRange(rangeLocation?: Word.RangeLocation | "Whole" | "Start" | "End" | "Before" | "After" | "Content"): Word.Range;

参数

rangeLocation

Word.RangeLocation | "Whole" | "Start" | "End" | "Before" | "After" | "Content"

可选。 范围位置必须为“Whole”、“Start”、“End”、“Before”、“After”或“Content”。

返回

注解

[ API 集:WordApi 1.3 ]

getReviewedText(changeTrackingVersion)

根据 ChangeTrackingVersion 选择获取审阅的文本。

getReviewedText(changeTrackingVersion?: Word.ChangeTrackingVersion): OfficeExtension.ClientResult<string>;

参数

changeTrackingVersion
Word.ChangeTrackingVersion

可选。 该值必须为“Original”或“Current”。 默认值为“Current”。

返回

注解

[ API 集:WordApi 1.4 ]

getReviewedText(changeTrackingVersionString)

根据 ChangeTrackingVersion 选择获取审阅的文本。

getReviewedText(changeTrackingVersionString?: "Original" | "Current"): OfficeExtension.ClientResult<string>;

参数

changeTrackingVersionString

"Original" | "Current"

可选。 该值必须为“Original”或“Current”。 默认值为“Current”。

返回

注解

[ API 集:WordApi 1.4 ]

getTextRanges(endingMarks, trimSpacing)

使用标点符号和/或其他结束标记获取内容控件中的文本范围。

getTextRanges(endingMarks: string[], trimSpacing?: boolean): Word.RangeCollection;

参数

endingMarks

string[]

必填。 标点符号和/或其他结束标记作为字符串数组。

trimSpacing

boolean

可选。 指示是否剪裁 (空格、制表符、分栏符和段落结束标记) 范围集合中返回的范围的开头和末尾的间距字符。 默认值为 false,指示范围集合中包含范围开头和末尾的间距字符。

返回

注解

[ API 集:WordApi 1.3 ]

getTrackedChanges()

获取内容控件中 TrackedChange 对象的集合。

getTrackedChanges(): Word.TrackedChangeCollection;

返回

注解

[ API 集:WordApi 1.6 ]

insertBreak(breakType, insertLocation)

在主文档的指定位置插入分隔符。 此方法不能与“RichTextTable”、“RichTextTableRow”和“RichTextTableCell”内容控件一起使用。

insertBreak(breakType: Word.BreakType | "Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line", insertLocation: Word.InsertLocation.start | Word.InsertLocation.end | Word.InsertLocation.before | Word.InsertLocation.after | "Start" | "End" | "Before" | "After"): void;

参数

breakType

Word.BreakType | "Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line"

必填。 中断的类型。

insertLocation

start | end | before | after | "Start" | "End" | "Before" | "After"

必填。 该值必须是“Start”、“End”、“Before”或“After”。

返回

void

注解

[ API 集:WordApi 1.1 ]

示例

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the id property for all of content controls.
    contentControls.load('id');
    
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    // We now will have access to the content control collection.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to insert a page break after the first content control.
        contentControls.items[0].insertBreak(Word.BreakType.page, Word.InsertLocation.after);
        
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Inserted a page break after the first content control.');    
    }
});

insertFileFromBase64(base64File, insertLocation)

将文档插入到位于指定位置的内容控件中。

insertFileFromBase64(base64File: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;

参数

base64File

string

必填。 .docx 文件的 Base64 编码内容。

insertLocation

replace | start | end | "Replace" | "Start" | "End"

必填。 该值必须为“Replace”、“Start”或“End”。 “Replace”不能与“RichTextTable”和“RichTextTableRow”内容控件一起使用。

返回

注解

[ API 集:WordApi 1.1 ]

注意:如果要插入的文档在窗体字段中) 可能包含 ActiveX 控件 (,则不支持插入。 请考虑将此类窗体字段替换为适合你的方案的内容控件或其他选项。

insertHtml(html, insertLocation)

将 HTML 插入到内容控件中的指定位置。

insertHtml(html: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;

参数

html

string

必填。 要插入到内容控件中的 HTML。

insertLocation

replace | start | end | "Replace" | "Start" | "End"

必填。 该值必须为“Replace”、“Start”或“End”。 “Replace”不能与“RichTextTable”和“RichTextTableRow”内容控件一起使用。

返回

注解

[ API 集:WordApi 1.1 ]

示例

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the id property for all of the content controls.
    contentControls.load('id');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to put HTML into the contents of the first content control.
        contentControls.items[0].insertHtml(
            '<strong>HTML content inserted into the content control.</strong>',
            'Start');
    
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Inserted HTML in the first content control.');
    }
});

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

将嵌入式图片插入到内容控件中的指定位置。

insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.InlinePicture;

参数

base64EncodedImage

string

必填。 要插入内容控件中的 Base64 编码图像。

insertLocation

replace | start | end | "Replace" | "Start" | "End"

必填。 该值必须为“Replace”、“Start”或“End”。 “Replace”不能与“RichTextTable”和“RichTextTableRow”内容控件一起使用。

返回

注解

[ API 集:WordApi 1.2 ]

insertOoxml(ooxml, insertLocation)

将 OOXML 插入到指定位置的内容控件中。

insertOoxml(ooxml: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;

参数

ooxml

string

必填。 要插入到内容控件的 OOXML。

insertLocation

replace | start | end | "Replace" | "Start" | "End"

必填。 该值必须为“Replace”、“Start”或“End”。 “Replace”不能与“RichTextTable”和“RichTextTableRow”内容控件一起使用。

返回

注解

[ API 集:WordApi 1.1 ]

示例

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the id property for all of the content controls.
    contentControls.load('id');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to put OOXML into the contents of the first content control.
        contentControls.items[0].insertOoxml("<pkg:package xmlns:pkg='http://schemas.microsoft.com/office/2006/xmlPackage'><pkg:part pkg:name='/_rels/.rels' pkg:contentType='application/vnd.openxmlformats-package.relationships+xml' pkg:padding='512'><pkg:xmlData><Relationships xmlns='http://schemas.openxmlformats.org/package/2006/relationships'><Relationship Id='rId1' Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument' Target='word/document.xml'/></Relationships></pkg:xmlData></pkg:part><pkg:part pkg:name='/word/document.xml' pkg:contentType='application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml'><pkg:xmlData><w:document xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' ><w:body><w:p><w:pPr><w:spacing w:before='360' w:after='0' w:line='480' w:lineRule='auto'/><w:rPr><w:color w:val='70AD47' w:themeColor='accent6'/><w:sz w:val='28'/></w:rPr></w:pPr><w:r><w:rPr><w:color w:val='70AD47' w:themeColor='accent6'/><w:sz w:val='28'/></w:rPr><w:t>This text has formatting directly applied to achieve its font size, color, line spacing, and paragraph spacing.</w:t></w:r></w:p></w:body></w:document></pkg:xmlData></pkg:part></pkg:package>", "End");
    
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Inserted OOXML in the first content control.');
    }
});  

// Read "Create better add-ins for Word with Office Open XML" for guidance on working with OOXML.
// https://learn.microsoft.com/office/dev/add-ins/word/create-better-add-ins-for-word-with-office-open-xml

insertParagraph(paragraphText, insertLocation)

在指定位置插入段落。

insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation.start | Word.InsertLocation.end | Word.InsertLocation.before | Word.InsertLocation.after | "Start" | "End" | "Before" | "After"): Word.Paragraph;

参数

paragraphText

string

必填。 要插入的段落文本。

insertLocation

start | end | before | after | "Start" | "End" | "Before" | "After"

必填。 该值必须是“Start”、“End”、“Before”或“After”。 “Before”和“After”不能与“RichTextTable”、“RichTextTableRow”和“RichTextTableCell”内容控件一起使用。

返回

注解

[ API 集:WordApi 1.1 ]

示例

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the id property for all of the content controls.
    contentControls.load('id');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to insert a paragraph after the first content control.
        contentControls.items[0].insertParagraph('Text of the inserted paragraph.', 'After');
    
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Inserted a paragraph after the first content control.');
    }
});  

insertTable(rowCount, columnCount, insertLocation, values)

将包含指定行数和列数的 table 插入 contentControl 中或在其旁边插入。

insertTable(rowCount: number, columnCount: number, insertLocation: Word.InsertLocation.start | Word.InsertLocation.end | Word.InsertLocation.before | Word.InsertLocation.after | "Start" | "End" | "Before" | "After", values?: string[][]): Word.Table;

参数

rowCount

number

必填。 表格的行数。

columnCount

number

必填。 表格的列数。

insertLocation

start | end | before | after | "Start" | "End" | "Before" | "After"

必填。 该值必须是“Start”、“End”、“Before”或“After”。 “Before”和“After”不能与“RichTextTable”、“RichTextTableRow”和“RichTextTableCell”内容控件一起使用。

values

string[][]

可选的二维数组。 如果指定数组中的对应字符串,则填充单元格。

返回

注解

[ API 集:WordApi 1.3 ]

insertText(text, insertLocation)

将文本插入到内容控件中的指定位置。

insertText(text: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;

参数

text

string

必填。 要插入到内容控件中的文本。

insertLocation

replace | start | end | "Replace" | "Start" | "End"

必填。 该值必须为“Replace”、“Start”或“End”。 “Replace”不能与“RichTextTable”和“RichTextTableRow”内容控件一起使用。

返回

注解

[ API 集:WordApi 1.1 ]

示例

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the id property for all of the content controls.
    contentControls.load('id');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to replace text in the first content control.
        contentControls.items[0].insertText('Replaced text in the first content control.', 'Replace');
    
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Replaced text in the first content control.');
    }
});  

// The Silly stories add-in sample shows how to use the insertText method.
// https://aka.ms/sillystorywordaddin

load(options)

将命令加入队列以加载对象的指定属性。 阅读属性前必须先调用 context.sync()

load(options?: Word.Interfaces.ContentControlLoadOptions): Word.ContentControl;

参数

options
Word.Interfaces.ContentControlLoadOptions

提供要加载对象的属性的选项。

返回

示例

// Load all of the content control properties
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the id property for all of the content controls.
    contentControls.load('id');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    } else {
        // Queue a command to load the properties on the first content control.
        contentControls.items[0].load(  'appearance,' +
                                        'cannotDelete,' +
                                        'cannotEdit,' +
                                        'id,' +
                                        'placeHolderText,' +
                                        'removeWhenEdited,' +
                                        'title,' +
                                        'text,' +
                                        'type,' +
                                        'style,' +
                                        'tag,' +
                                        'font/size,' +
                                        'font/name,' +
                                        'font/color');             
    
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Property values of the first content control:' + 
            '   ----- appearance: ' + contentControls.items[0].appearance + 
            '   ----- cannotDelete: ' + contentControls.items[0].cannotDelete +
            '   ----- cannotEdit: ' + contentControls.items[0].cannotEdit +
            '   ----- color: ' + contentControls.items[0].color +
            '   ----- id: ' + contentControls.items[0].id +
            '   ----- placeHolderText: ' + contentControls.items[0].placeholderText +
            '   ----- removeWhenEdited: ' + contentControls.items[0].removeWhenEdited +
            '   ----- title: ' + contentControls.items[0].title +
            '   ----- text: ' + contentControls.items[0].text +
            '   ----- type: ' + contentControls.items[0].type +
            '   ----- style: ' + contentControls.items[0].style +
            '   ----- tag: ' + contentControls.items[0].tag +
            '   ----- font size: ' + contentControls.items[0].font.size +
            '   ----- font name: ' + contentControls.items[0].font.name +
            '   ----- font color: ' + contentControls.items[0].font.color);
    }
});  

load(propertyNames)

将命令加入队列以加载对象的指定属性。 阅读属性前必须先调用 context.sync()

load(propertyNames?: string | string[]): Word.ContentControl;

参数

propertyNames

string | string[]

逗号分隔的字符串或指定要加载的属性的字符串数组。

返回

load(propertyNamesAndPaths)

将命令加入队列以加载对象的指定属性。 阅读属性前必须先调用 context.sync()

load(propertyNamesAndPaths?: {
            select?: string;
            expand?: string;
        }): Word.ContentControl;

参数

propertyNamesAndPaths

{ select?: string; expand?: string; }

propertyNamesAndPaths.select 是一个逗号分隔的字符串,指定要加载的属性,是 propertyNamesAndPaths.expand 一个逗号分隔的字符串,指定要加载的导航属性。

返回

resetState()

注意

此 API 以预览状态提供给开发者,可能根据我们收到的反馈更改。 请勿在生产环境中使用此 API。

重置内容控件的状态。

resetState(): void;

返回

void

注解

[ API 集:WordApi BETA (仅预览版) ]

search(searchText, searchOptions)

对内容控件对象的作用域使用指定的 SearchOptions 执行搜索。 搜索结果是 range 对象的集合。

search(searchText: string, searchOptions?: Word.SearchOptions | {
            ignorePunct?: boolean;
            ignoreSpace?: boolean;
            matchCase?: boolean;
            matchPrefix?: boolean;
            matchSuffix?: boolean;
            matchWholeWord?: boolean;
            matchWildcards?: boolean;
        }): Word.RangeCollection;

参数

searchText

string

必填。 搜索文本。

searchOptions

Word.SearchOptions | { ignorePunct?: boolean; ignoreSpace?: boolean; matchCase?: boolean; matchPrefix?: boolean; matchSuffix?: boolean; matchWholeWord?: boolean; matchWildcards?: boolean; }

可选。 用于搜索的选项。

返回

注解

[ API 集:WordApi 1.1 ]

示例

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the id property for all of the content controls.
    contentControls.load('id');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to select the first content control.
        contentControls.items[0].select();
    
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Selected the first content control.');
    }
});  

select(selectionMode)

选择内容控件。 这会导致 Word 滚动到选定内容。

select(selectionMode?: Word.SelectionMode): void;

参数

selectionMode
Word.SelectionMode

可选。 选择模式必须为“Select”、“Start”或“End”。 “Select”为默认值。

返回

void

注解

[ API 集:WordApi 1.1 ]

select(selectionModeString)

选择内容控件。 这会导致 Word 滚动到选定内容。

select(selectionModeString?: "Select" | "Start" | "End"): void;

参数

selectionModeString

"Select" | "Start" | "End"

可选。 选择模式必须为“Select”、“Start”或“End”。 “Select”为默认值。

返回

void

注解

[ API 集:WordApi 1.1 ]

set(properties, options)

同时设置对象的多个属性。 可以传递具有相应属性的纯对象,也可以传递同一类型的另一个 API 对象。

set(properties: Interfaces.ContentControlUpdateData, options?: OfficeExtension.UpdateOptions): void;

参数

properties
Word.Interfaces.ContentControlUpdateData

一个 JavaScript 对象,其属性按同构方式构造为调用方法的对象的属性。

options
OfficeExtension.UpdateOptions

提供一个选项,用于在 properties 对象尝试设置任何只读属性时禁止显示错误。

返回

void

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/insert-and-change-content-controls.yaml

// Adds title and colors to odd and even content controls and changes their appearance.
await Word.run(async (context) => {
  // Get the complete sentence (as range) associated with the insertion point.
  let evenContentControls = context.document.contentControls.getByTag("even");
  let oddContentControls = context.document.contentControls.getByTag("odd");
  evenContentControls.load("length");
  oddContentControls.load("length");

  await context.sync();

  for (let i = 0; i < evenContentControls.items.length; i++) {
    // Change a few properties and append a paragraph
    evenContentControls.items[i].set({
      color: "red",
      title: "Odd ContentControl #" + (i + 1),
      appearance: Word.ContentControlAppearance.tags
    });
    evenContentControls.items[i].insertParagraph("This is an odd content control", "End");
  }

  for (let j = 0; j < oddContentControls.items.length; j++) {
    // Change a few properties and append a paragraph
    oddContentControls.items[j].set({
      color: "green",
      title: "Even ContentControl #" + (j + 1),
      appearance: "Tags"
    });
    oddContentControls.items[j].insertHtml("This is an <b>even</b> content control", "End");
  }

  await context.sync();
});

set(properties)

基于现有的已加载对象,同时对对象设置多个属性。

set(properties: Word.ContentControl): void;

参数

properties
Word.ContentControl

返回

void

setState(contentControlState)

注意

此 API 以预览状态提供给开发者,可能根据我们收到的反馈更改。 请勿在生产环境中使用此 API。

设置内容控件的状态。

setState(contentControlState: Word.ContentControlState): void;

参数

contentControlState
Word.ContentControlState

要设置的状态。

返回

void

注解

[ API 集:WordApi BETA (仅预览版) ]

setState(contentControlStateString)

注意

此 API 以预览状态提供给开发者,可能根据我们收到的反馈更改。 请勿在生产环境中使用此 API。

设置内容控件的状态。

setState(contentControlStateString: "Error" | "Warning"): void;

参数

contentControlStateString

"Error" | "Warning"

要设置的状态。

返回

void

注解

[ API 集:WordApi BETA (仅预览版) ]

split(delimiters, multiParagraphs, trimDelimiters, trimSpacing)

使用分隔符将内容控件拆分为各个子范围。

split(delimiters: string[], multiParagraphs?: boolean, trimDelimiters?: boolean, trimSpacing?: boolean): Word.RangeCollection;

参数

delimiters

string[]

必填。 分隔符作为字符串数组。

multiParagraphs

boolean

可选。 指示返回的子区域是否可以涵盖多个段落。 默认值为 false,指示段落边界也用作分隔符。

trimDelimiters

boolean

可选。 指示是否从范围集合中的区域剪裁分隔符。 默认值为 false,指示分隔符包含在范围集合中返回的区域中。

trimSpacing

boolean

可选。 指示是否剪裁 (空格、制表符、分栏符和段落结束标记) 范围集合中返回的范围的开头和末尾的间距字符。 默认值为 false,指示范围集合中包含范围开头和末尾的间距字符。

返回

注解

[ API 集:WordApi 1.3 ]

toJSON()

重写 JavaScript toJSON() 方法,以便在将 API 对象传递给 JSON.stringify()时提供更有用的输出。 JSON.stringify (,反过来又调用toJSON传递给它的 对象的 方法。) 而原始Word。ContentControl 对象是一个 API 对象,toJSON该方法返回一个纯 JavaScript 对象, (类型为 Word.Interfaces.ContentControlData) ,其中包含原始对象中任何已加载子属性的浅表副本。

toJSON(): Word.Interfaces.ContentControlData;

返回

track()

根据文档中的相应更改来跟踪对象,以便进行自动调整。 此调用是 context.trackedObjects.add (thisObject) 的简写。 如果跨 .sync 调用和“.run”批处理的顺序执行外部使用此对象,并在设置属性或调用对象方法时收到“InvalidObjectPath”错误,则需要在首次创建对象时将该对象添加到跟踪的对象集合。 如果此对象是集合的一部分,则还应跟踪父集合。

track(): Word.ContentControl;

返回

untrack()

释放与此对象关联的内存(如果先前已跟踪过)。 此调用是 context.trackedObjects.remove (thisObject) 的简写。 拥有许多跟踪对象会降低主机应用程序的速度,因此请在使用完毕后释放所添加的任何对象。 在内存发布生效之前,需要调用 context.sync()

untrack(): Word.ContentControl;

返回

事件详细信息

onCommentAdded

注意

此 API 以预览状态提供给开发者,可能根据我们收到的反馈更改。 请勿在生产环境中使用此 API。

在添加新注释时发生。

readonly onCommentAdded: OfficeExtension.EventHandlers<Word.CommentEventArgs>;

事件类型

注解

[ API 集:WordApi BETA (仅预览版) ]

onCommentChanged

注意

此 API 以预览状态提供给开发者,可能根据我们收到的反馈更改。 请勿在生产环境中使用此 API。

更改批注或其回复时发生。

readonly onCommentChanged: OfficeExtension.EventHandlers<Word.CommentEventArgs>;

事件类型

注解

[ API 集:WordApi BETA (仅预览版) ]

onCommentDeselected

注意

此 API 以预览状态提供给开发者,可能根据我们收到的反馈更改。 请勿在生产环境中使用此 API。

在取消选择批注时发生。

readonly onCommentDeselected: OfficeExtension.EventHandlers<Word.CommentEventArgs>;

事件类型

注解

[ API 集:WordApi BETA (仅预览版) ]

onCommentSelected

注意

此 API 以预览状态提供给开发者,可能根据我们收到的反馈更改。 请勿在生产环境中使用此 API。

在选择批注时发生。

readonly onCommentSelected: OfficeExtension.EventHandlers<Word.CommentEventArgs>;

事件类型

注解

[ API 集:WordApi BETA (仅预览版) ]

onDataChanged

在更改内容控件中的数据时发生。 若要获取新文本,请在处理程序中加载此内容控件。 若要获取旧文本,请不要加载它。

readonly onDataChanged: OfficeExtension.EventHandlers<Word.ContentControlDataChangedEventArgs>;

事件类型

注解

[ API 集:WordApi 1.5 ]

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/content-control-ondatachanged-event.yaml

await Word.run(async (context) => {
  const contentControls = context.document.contentControls;
  contentControls.load("items");
  await context.sync();

  // Register the onDataChanged event handler on each content control.
  if (contentControls.items.length === 0) {
    console.log("There aren't any content controls in this document so can't register event handlers.");
  } else {
    for (let i = 0; i < contentControls.items.length; i++) {
      eventContexts[i] = contentControls.items[i].onDataChanged.add(contentControlDataChanged);
      contentControls.items[i].track();
    }

    await context.sync();

    console.log("Added event handlers for when data is changed in content controls.");
  }
});

...

async function contentControlDataChanged(event: Word.ContentControlDataChangedEventArgs) {
  await Word.run(async (context) => {
    console.log(`${event.eventType} event detected. IDs of content controls where data was changed:`);
    console.log(event.ids);
  });
}

onDeleted

删除内容控件时发生。 请勿在处理程序中加载此内容控件,否则将无法获取其原始属性。

readonly onDeleted: OfficeExtension.EventHandlers<Word.ContentControlDeletedEventArgs>;

事件类型

注解

[ API 集:WordApi 1.5 ]

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/content-control-ondeleted-event.yaml

await Word.run(async (context) => {
  const contentControls = context.document.contentControls;
  contentControls.load("items");
  await context.sync();

  // Register the onDeleted event handler on each content control.
  if (contentControls.items.length === 0) {
    console.log("There aren't any content controls in this document so can't register event handlers.");
  } else {
    for (let i = 0; i < contentControls.items.length; i++) {
      eventContexts[i] = contentControls.items[i].onDeleted.add(contentControlDeleted);
      contentControls.items[i].track();
    }

    await context.sync();

    console.log("Added event handlers for when content controls are deleted.");
  }
});

...

async function contentControlDeleted(event: Word.ContentControlDeletedEventArgs) {
  await Word.run(async (context) => {
    console.log(`${event.eventType} event detected. IDs of content controls that were deleted:`);
    console.log(event.ids);
  });
}

onEntered

在输入内容控件时发生。

readonly onEntered: OfficeExtension.EventHandlers<Word.ContentControlEnteredEventArgs>;

事件类型

注解

[ API 集:WordApi 1.5 ]

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/content-control-onentered-event.yaml

await Word.run(async (context) => {
  const contentControls = context.document.contentControls;
  contentControls.load("items");
  await context.sync();

  // Register the onEntered event handler on each content control.
  if (contentControls.items.length === 0) {
    console.log("There aren't any content controls in this document so can't register event handlers.");
  } else {
    for (let i = 0; i < contentControls.items.length; i++) {
      eventContexts[i] = contentControls.items[i].onEntered.add(contentControlEntered);
      contentControls.items[i].track();
    }

    await context.sync();

    console.log("Added event handlers for when the cursor is placed in content controls.");
  }
});

...

async function contentControlEntered(event: Word.ContentControlEnteredEventArgs) {
  await Word.run(async (context) => {
    console.log(`${event.eventType} event detected. ID of content control that was entered: ${event.ids[0]}`);
  });
}

onExited

在退出内容控件时发生,例如,当光标离开内容控件时。

readonly onExited: OfficeExtension.EventHandlers<Word.ContentControlExitedEventArgs>;

事件类型

注解

[ API 集:WordApi 1.5 ]

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/content-control-onexited-event.yaml

await Word.run(async (context) => {
  const contentControls = context.document.contentControls;
  contentControls.load("items");
  await context.sync();

  // Register the onExited event handler on each content control.
  if (contentControls.items.length === 0) {
    console.log("There aren't any content controls in this document so can't register event handlers.");
  } else {
    for (let i = 0; i < contentControls.items.length; i++) {
      eventContexts[i] = contentControls.items[i].onExited.add(contentControlExited);
      contentControls.items[i].track();
    }

    await context.sync();

    console.log("Added event handlers for when the cursor is removed from within content controls.");
  }
});

...

async function contentControlExited(event: Word.ContentControlExitedEventArgs) {
  await Word.run(async (context) => {
    console.log(`${event.eventType} event detected. ID of content control that was exited: ${event.ids[0]}`);
  });
}

onSelectionChanged

更改内容控件中的选择时发生。

readonly onSelectionChanged: OfficeExtension.EventHandlers<Word.ContentControlSelectionChangedEventArgs>;

事件类型

注解

[ API 集:WordApi 1.5 ]

示例

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/content-control-onselectionchanged-event.yaml

await Word.run(async (context) => {
  const contentControls = context.document.contentControls;
  contentControls.load("items");
  await context.sync();

  if (contentControls.items.length === 0) {
    console.log("There aren't any content controls in this document so can't register event handlers.");
  } else {
    for (let i = 0; i < contentControls.items.length; i++) {
      eventContexts[i] = contentControls.items[i].onSelectionChanged.add(contentControlSelectionChanged);
      contentControls.items[i].track();
    }

    await context.sync();

    console.log("Added event handlers for when selections are changed in content controls.");
  }
});

...

async function contentControlSelectionChanged(event: Word.ContentControlSelectionChangedEventArgs) {
  await Word.run(async (context) => {
    console.log(`${event.eventType} event detected. IDs of content controls where selection was changed:`);
    console.log(event.ids);
  });
}