Sof*_*mur 5 ms-office office-js
我想创建一个文本区域,用户可以在其中选择文本的一部分,我将根据他们的选择做出反应。所以我需要
1)获取选择文本的开始和结束位置
2)获取焦点的位置,如果它在textarea中并且没有选择
似乎不同的浏览器执行此操作的功能有所不同。那么谁能告诉我在 Office 加载项中执行此操作的方法是什么?
我尝试了以下两种方法(即选择 中的部分文本myTextarea,单击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
}
})();
Run Code Online (Sandbox Code Playgroud)
另外,如果有人能告诉我如何通过代码实现以下内容那就太好了:
1)从开始和结束位置选择文本的一部分
2)将焦点设置在textarea的某个位置
编辑1:
我刚刚window.getSelection()在我的 Excel 加载项中尝试过:
function showselection() {
var a = window.getSelection();
var b = window.getSelection().toString();
var c = window.getSelection().getRangeAt(0);
}
Run Code Online (Sandbox Code Playgroud)
在文本区域中选择文本后,点击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.看起来选择还没有被成功捕获......
这是没有 Excel 加载项框架的JSBin ,它返回与上面几乎相同的结果。
小智 2
使用 JQuery。
例如,以下两行获取插入符号位置:
function showselection() {
console.log($('#myTextarea')[0].selectionStart);
console.log($('#myTextarea')[0].selectionEnd);
}
Run Code Online (Sandbox Code Playgroud)
有一些插件:
https://github.com/localhost/jquery-fieldselection
http://madapaja.github.io/jquery.selection/
第二个有几个带有按钮的简短示例(我们可能会失去选择)。您可以使用他们的 API,或者查看他们的代码以查看他们调用了哪些 JQuery 函数。