Insert text before and after selection in a contenteditable

Is there a way to insert text similar to bbcode before and after the selected text in a contenteditable div? I've seen many answers for textarea, but the code does not work with a contenteditable div. IE support is not needed.


The approach I'd suggest is:

  • Obtain a range from the selection
  • Insert a text node at the end of the range
  • Insert another text node at the start of the range
  • Reselect the original text
  • The following demo will work in all major browsers except IE <= 8.

    Demo: http://jsfiddle.net/8WEru/

    Code:

    function surroundSelection(textBefore, textAfter) {
        if (window.getSelection) {
            var sel = window.getSelection();
            if (sel.rangeCount > 0) {
                var range = sel.getRangeAt(0);
                var startNode = range.startContainer, startOffset = range.startOffset;
    
                var startTextNode = document.createTextNode(textBefore);
                var endTextNode = document.createTextNode(textAfter);
    
                var boundaryRange = range.cloneRange();
                boundaryRange.collapse(false);
                boundaryRange.insertNode(endTextNode);
                boundaryRange.setStart(startNode, startOffset);
                boundaryRange.collapse(true);
                boundaryRange.insertNode(startTextNode);
    
                // Reselect the original text
                range.setStartAfter(startTextNode);
                range.setEndBefore(endTextNode);
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    }
    

    If I understand from your comments the new goal, you have a selection and want to surround it by an element. Then the surroundContents method of range should work:

    var selection = window.getSelection();
    var range = selection.getRangeAt(0);
    var strong = document.createElement('strong');
    range.surroundContents(strong);
    
    链接地址: http://www.djcxy.com/p/41634.html

    上一篇: 如何从jquery中的文本区域获取选定的文本?

    下一篇: 在contenteditable的选择之前和之后插入文本