在文本区域中获取和设置文本选择

Getting and setting of a text selection in a textarea

我想创建一个文本区域,用户可以在其中 select 部分文本,我会根据他们的 selection 做出反应。所以我需要

1) 获取select离子文本的开始和结束位置

2) 获取焦点的位置,如果在textarea中且没有selection

似乎每个浏览器的功能都不一样。那么谁能告诉我在 Office 加载项中执行此操作的方法是什么?

我试过以下2种方法(即selectmyTextarea中的一部分文字,点击button,然后调试代码),都没有似乎是正确的功能。

(function() {
    "use strict";

    Office.initialize = function(reason) {
        $(document).ready(function() {
            app.initialize();
            $('#button').click(showSelection);
        });
    };

    function showSelection() {
        // way 1
        console.log(document.selection); // undefined
        document.getElementById("myTextarea").focus();
        var sel = document.selection.createRange(); // Uncaught TypeError: Cannot read property 'createRange' of undefined
        selectedText = sel.text;
        // way 2 
        console.log(document.getElementById("myTextarea").selectionstart); // undefined
        console.log(document.getElementById("myTextarea").selectionend); // undefined
    }
})();

另外,如果有人能告诉我如何通过代码实现以下内容,那就太好了:

1) select 文本的一部分,从开始位置到结束位置

2) 将焦点设置在textarea的某个位置

编辑 1:

我刚刚在我的 Excel 加载项中尝试了 window.getSelection()

function showselection() {
    var a = window.getSelection();
    var b = window.getSelection().toString();
    var c = window.getSelection().getRangeAt(0);
}

在文本区域select输入文本后,点击button,我一步步调试:第一行制作a a = Selection {anchorNode: null, anchorOffset: 0, focusNode: null, focusOffset: 0, is ...;第二行返回 "",第三行出错 Home.js:19 Uncaught IndexSizeError: Failed to execute 'getRangeAt' on 'Selection': 0 is not a valid index. 看起来 selection 没有被成功捕获...

这里是JSBin没有Excel外接框架,returns和上面几乎一样的结果。

Office 的 JavaScript API 的一个主要特征是它们遵循异步模型(您在上面为 showSelection() 编写的代码似乎是同步的)。我建议阅读 Excel and Word JS API 概述页面以了解它们的工作原理。例如,您可以通过以下方式从所选内容中获取文本:

Word.run(function (context) {
    var myRange = context.document.getSelection();
    context.load(myRange, 'text');
    return context.sync().then(function () {
        log("Selection contents: " + myRange.text);
    });
})

那么对于您问题的其他细节,请按照我的评论中的要求进行澄清。谢谢!

-Michael(Office 加载项的 PM)

如果想要的选择只是 HTML 页面中选择的文本(而不是用户在 Excel/Word 中的选择),那么有一些好的 Whosebug answers about accessing that selection.

使用JQuery.

例如,以下两行获取插入符位置:

function showselection() {
    console.log($('#myTextarea')[0].selectionStart);
    console.log($('#myTextarea')[0].selectionEnd);
}

有一些插件:

https://github.com/localhost/jquery-fieldselection

http://madapaja.github.io/jquery.selection/

第二个有几个带有按钮的简短样本(我们可能会失去选择)。您可以使用他们的 API,或查看他们的代码以查看他们调用了哪些 JQuery 函数。