Contenteditable - extract text from caret to end of element

泄露秘密 提交于 2019-12-04 14:11:03

You can do this by creating a Range object that encompasses the content from the caret to the end of the containing block element and calling its extractContents() method:

function getBlockContainer(node) {
    while (node) {
        // Example block elements below, you may want to add more
        if (node.nodeType == 1 && /^(P|H[1-6]|DIV)$/i.test(node.nodeName)) {
            return node;
        }
        node = node.parentNode;
    }
}

function extractBlockContentsFromCaret() {
    var sel = window.getSelection();
    if (sel.rangeCount) {
        var selRange = sel.getRangeAt(0);
        var blockEl = getBlockContainer(selRange.endContainer);
        if (blockEl) {
            var range = selRange.cloneRange();
            range.selectNodeContents(blockEl);
            range.setStart(selRange.endContainer, selRange.endOffset);
            return range.extractContents();
        }
    }
}

This won't work in IE <= 8, which doesn't support Range or the same selection object as other browsers. You can use Rangy (which you mentioned) to provide IE support. Just replace window.getSelection() with rangy.getSelection().

jsFiddle: http://jsfiddle.net/LwXvk/3/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!