【问题标题】:Office JavaScript API: Binding a substring of the selectionOffice JavaScript API:绑定选择的子字符串
【发布时间】:2017-08-09 02:00:46
【问题描述】:

问题

使用 MS Word 中的 Office JavaScript API,我知道如何使用 document.bindings.addFromSelectionAsync 绑定当前选择,但是,我还没有找到绑定当前选择的子字符串的方法。

例如,如果用户选择了整个段落,而我只想绑定第一个单词,我该如何做到这一点?

失败的方法

  1. 先绑定选择,再绑定子字符串,再移除第一个绑定:我还没找到绑定子字符串的方法。
  2. 先改选再用addFromSelectionAsync:我还没找到改选的方法。

【问题讨论】:

    标签: office-js


    【解决方案1】:

    在 Word 中,Binding 在物理上由文档中的内容控件表示,因此通常方法是在您需要的地方创建内容控件(在这种情况下,选择中的第一个单词) ) 并为其分配一个标题,以便最终您可以使用 bindings.addFromNamedItem 方法创建绑定。

    总结:

    1. 获取要在其中创建绑定的范围。在这种情况下,您需要选择中的第一个单词。
    2. 获得范围后,用内容控件包装它并指定标题。
    3. 最后,使用带有该标题的 addFromNamedItem。

    这是一个示例:

     Word.run(function (context) {
            //first we get the first word in the selection by using the split method, and using space as delimiter and then we add a content control
            var firstWordContentControl = context.document.getSelection().split([" "], true, false, true).getFirst().insertContentControl();
    //let's add a title.
            firstWordContentControl.title = "BindingID";
            return context.sync()
                .then(function () { 
    //we reuse the title to create the binding.
                    Office.context.document.bindings.addFromNamedItemAsync("BindingID", "text", {}, function (result) {
                        console.log(result.status);
                        if (result.status == "succeeded") { 
                            // lets create an event!
                            result.value.addHandlerAsync(Office.EventType.BindingSelectionChanged, function () { 
                                console.log("event happened");
                            })
                        }
                     });
                })
        })
            .catch(function(exception) {
            OfficeHelpers.Utilities.log(exception);
        })

    希望这会有所帮助。 -胡安

    【讨论】:

      【解决方案2】:

      虽然不是您正在寻找的,但Word API 为您提供了完成此任务所需的大部分内容。

      可以使用document.getSelection() 获取用户当前的选择。这将返回一个Range object。从这里您可以深入了解Paragraphschild ranges(基于分词规则)等等。

      一旦您有一个反映您正在寻找的文本的 Range 对象,range.Select() 将导致在 UI 中选择该范围。从这里您可以使用addFromSelectionAsync 来建立您的绑定。

      【讨论】:

        猜你喜欢
        • 2018-05-25
        • 1970-01-01
        • 1970-01-01
        • 2016-05-18
        • 1970-01-01
        • 2015-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多