如何使用 TypeScript 在 contenteditable 的插入符号位置插入

How to insert at caret position of contenteditable using TypeScript

我曾经有过这样的代码:

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 only/specific 并且已被删除:https://msdn.microsoft.com/en-us/library/ms535869(v=vs.85).aspx