简体   繁体   中英

Contenteditable - extract text from caret to end of element

after skimming all possible questions and answers, i'll try it this way.

I'm programming an RTE, but didn't manage to successfully extract text in a contenteditable element. The reason for this is, that each browser handles nodes and keypress (#13) events in a slightly different way (as ex.g. one creates 'br', the other 'div', 'p', etc.) To keep this all consistent, I'm writing a cross-browser editor which kills all default action with e.preventDefault();

Following scenario:

1) User hits the #13 key (check)

2) Caret position detected (check)

3) create new p(aragraph) after the element the caret's in (check)

4) if text(node(s)) between caret and the element's end, extract it (? ? ?)

5) put text(node(s)) to newly created p(aragraph) (check)

As you can imagine, everything works except point 4.

There's a similar functionality in the well-known js rangy library, where a specific selection is being extracted.

What i need is following: Get and extract all text (with tags of course, so splitBoundaries) from the caret on to the end of the contenteditable paragraph (p, h1, h2, ...) element.

Any clues, hints or snippets are welcome! Thanks in advance.

Kind regards, p

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM