2017-08-10 43 views
0

鑑於一些範圍在Word文檔正文,我想設置當前選擇該範圍內的替換文本。控制從Javascript Word文檔中的選擇範圍外接

有誰知道我可以從外接使用JavaScript API控制一個Word文檔中的當前選擇?我似乎無法在文檔中發現了什麼:

https://dev.office.com/reference/add-ins/word/word-add-ins-reference-overview

我明白我可以使用context.document.getSelection()文檔中獲取當前的選擇,但我如何得到一個文件中的任何選擇或指定的哪一部分該文件被選中?如何以編程方式控制文檔中選擇的內容?

回答

1

獲取所選範圍用戶選擇:

// Run a batch operation against the Word object model. 
    Word.run(function (context) { 

     var range = context.document.getSelection();// Create a range proxy object for the current selection. 

     range.clear();                
     range.delete(); 

     // Synchronize the document state by executing the queued commands, and return a promise to indicate task completion. 
     return context.sync().then(function() { 

     range.styleBuiltIn = "Normal";                
     range.insertText("your text"); // Queue a command to insert the encrypted text instead the current text 
     }); 
    }) 

所以,如果你有多少已經在「範圍」:

// Run a batch operation against the Word object model. 
     Word.run(function (context) { 

      var range = context.document.getSelection(); // Create a range proxy object for the current selection. 
      context.load(range); 
      // Synchronize the document state by executing the queued commands,and return a promise to indicate task completion. 
      return context.sync().then(function() { 

       if (range.isEmpty) //Check if the selection is empty 
       { 
        return; 
       } 
       var html = range.getHtml(); 
       return context.sync().then(function() { 

        var htmlVal = html.value; //Get the selected text in HTML 
       }); 
      }); 
      }); 

要在選定的範圍內設定的用戶你不需要知道它。

**如果你不想把用戶的選擇,並希望改變只是在文檔某些部分,你可以同款選擇實現它,你可以找到有關的段落對象,你可以用這個在這裏做的更多信息: https://dev.office.com/reference/add-ins/word/paragraph

好運

+0

感謝@OriEng。這不是我所期待的,對不起。我會盡力澄清我的問題。我知道我可以在文檔中獲得當前選擇,但是如何通過文檔獲得選擇?像'new Word.Range(start,end)',其中'start'和'end'是文檔文本中的任何索引。 –

+0

@CraigSketchley'anyselection'是什麼意思?對不起我還是不明白你的問題 – OriEng

+0

不用擔心@OriEng。對不起,我沒有更清楚。簡而言之,我想以編程方式控制選擇。據我所知,我只能訪問用戶選擇的內容,但我的加載項如何選擇文檔的任何部分? –