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

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

color

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

contentControls

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

context

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

font

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

id

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

inlinePictures

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

paragraphs

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

parentContentControl

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

placeholderText

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

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

removeWhenEdited

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

style

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

tag

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

text

获取内容控件的文本。

title

指定内容控件的标题。

type

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

方法

clear()

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

delete(keepContent)

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

getHtml()

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

getOoxml()

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

insertBreak(breakType, insertLocation)

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

insertFileFromBase64(base64File, insertLocation)

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

insertHtml(html, insertLocation)

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

insertOoxml(ooxml, insertLocation)

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

insertParagraph(paragraphText, insertLocation)

在指定位置插入段落。

insertText(text, insertLocation)

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

load(options)

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

load(propertyNames)

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

load(propertyNamesAndPaths)

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

search(searchText, searchOptions)

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

select(selectionMode)

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

select(selectionModeString)

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

set(properties, options)

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

set(properties)

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

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()

属性详细信息

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 ]

color

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

color: string;

属性值

string

注解

[ API 集:WordApi 1.1 ]

contentControls

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

readonly contentControls: Word.ContentControlCollection;

属性值

注解

[ API 集:WordApi 1.1 ]

context

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

context: RequestContext;

属性值

font

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

readonly font: Word.Font;

属性值

注解

[ API 集:WordApi 1.1 ]

id

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

readonly id: number;

属性值

number

注解

[ API 集:WordApi 1.1 ]

inlinePictures

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

readonly inlinePictures: Word.InlinePictureCollection;

属性值

注解

[ API 集:WordApi 1.1 ]

paragraphs

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

readonly paragraphs: Word.ParagraphCollection;

属性值

注解

[ API 集:WordApi 1.1 ]

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

parentContentControl

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

readonly parentContentControl: Word.ContentControl;

属性值

注解

[ API 集:WordApi 1.1 ]

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 ]

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:", contentControls.items[0]);
    contentControls.items[0].delete(false);
    await context.sync();
  }
});

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);
    }
});

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.');
    }
});

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.');
    }
});  

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 一个逗号分隔的字符串,指定要加载的导航属性。

返回

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

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;

返回