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

如何使用TypeScript在contenteditable的插入符号位置插入,typescript,contenteditable,caret,Typescript,Contenteditable,Caret,我以前有这样的代码: this.insertNodeAtCaret = function(node) { var sel, range, html; function containerIsEditable(selection) { return $(selection.anchorNode).parent().hasClass("editable"); } if

我以前有这样的代码:

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中,选择被从文档()中删除,所以我不知道如何让它工作。。我尝试了window.getSelection(),但没有结果

任何帮助都将不胜感激:)

谢谢, 迈克尔

但在TypeScript 1.5中,选择从文档中删除

这是internet explorer特有的,并不是所有浏览器都可以使用。所以它被移除了。但是,您可以很容易地不安全地使用它(将
文档
视为
任何
)。以下是经过重构以无误编译的代码示例:

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);
    }
};
当然,这假设您知道自己在做什么,比编译器知道的要多

使现代化
如何查看浏览器之间的兼容性以及可用的内容

您可以在此处看到window.getSelection的兼容性图表:


document.selection
仅适用于IE/specific,已被删除:

谢谢。需要运行时支持使其与所有浏览器兼容的其他方式。意味着您需要一个运行时函数。选项有
polyfill
shim
。你所拥有的是一个垫片,它已经足够好了。我如何才能看到浏览器之间的兼容性以及可用的内容?谢谢