我以前有这样的代码:
this.insertNodeAtCaret = function(node) {
var sel, range, html;
function containerIsEditable(selection) {
return $(selection.anchorNode).parent().hasClass("editable");
}
if (window.getSelection) {
sel = window.getSelection();
// only if it is a caret otherwise it inserts
// anywhere!
if (containerIsEditable(sel) && sel.getRangeAt
&& sel.rangeCount) {
var previousPosition = sel.getRangeAt(0).startOffset;
sel.getRangeAt(0).insertNode(node);
}
}
else if (document.selection
&& document.selection.createRange) {
range = document.selection.createRange();
html = (node.nodeType == 3) ? node.data
: node.outerHTML;
range.pasteHTML(html);
}
};
但在 TypeScript 1.5 中,选择已从文档中删除(https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes),所以我不知道如何让它工作。我尝试使用 window.getSelection() 但没有结果
任何帮助将不胜感激:)
谢谢, 迈克尔
最佳答案
but in TypeScript 1.5 Selection was removed from Document
那是 Internet Explorer 特有的 并且并非对所有浏览器普遍可用。所以它被删除了。然而,您可以很容易地不安全地使用它(通过将document
视为any
)。这是重构后编译无误的代码示例:
const insertNodeAtCaret = function (node) {
const doc = document as any;
var sel, range, html;
function containerIsEditable(selection) {
return $(selection.anchorNode).parent().hasClass("editable");
}
if (window.getSelection) {
sel = window.getSelection();
// only if it is a caret otherwise it inserts
// anywhere!
if (containerIsEditable(sel) && sel.getRangeAt
&& sel.rangeCount) {
var previousPosition = sel.getRangeAt(0).startOffset;
sel.getRangeAt(0).insertNode(node);
}
}
else if (doc.selection
&& doc.selection.createRange) {
range = doc.selection.createRange();
html = (node.nodeType == 3) ? node.data
: node.outerHTML;
range.pasteHTML(html);
}
};
当然,这假设您知道自己在做什么,比编译器知道的更多。
更新
how can I see the compatibility of those among browsers and what is available
您可以在此处查看 window.getSelection 的兼容性图表:https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection
document.selection
仅适用于/特定于 IE,已被删除:https://msdn.microsoft.com/en-us/library/ms535869(v=vs.85).aspx
关于typescript - 如何使用 TypeScript 在 contenteditable 的插入符号位置插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34982381/