在contentEditable元素中插入HTML元素

Eli*_*lie 5 javascript jquery contenteditable

我有一个contentEditable div,我想插入HTML标签(一个简单的span元素).

是否有跨浏览器解决方案,允许我在div选择或光标位置插入这些标签.如果在页面上选择了其他内容(而不是在div中),我想将标记附加到div的末尾.

谢谢

Mau*_*cio 7

这是一个kickstart

// get the selection range (or cursor     position)
var range = window.getSelection().getRangeAt(0); 
// create a span
var newElement = document.createElement('span');
newElement.id = 'myId';
newElement.innerHTML = 'Hello World!';

// if the range is in #myDiv ;)
if(range.startContainer.parentNode.id==='myDiv') {
   // delete whatever is on the range
   range.deleteContents();
   // place your span
   range.insertNode(newElement);
}
Run Code Online (Sandbox Code Playgroud)

我没有IE但在firefox,chrome和safari上工作正常.也许你想玩range.startContainer只有在contentEditable div上进行选择才能继续.

编辑:根据quirksmode范围介绍,您必须将window.getSelection()部分更改为IE兼容.

var userSelection;
if (window.getSelection) {
    userSelection = window.getSelection();
}
else if (document.selection) { // should come last; Opera!
    userSelection = document.selection.createRange();
}
Run Code Online (Sandbox Code Playgroud)


Tim*_*own 7

以下将在所有主流浏览器(包括IE 6)中执行此操作.它还将处理选择结束位于您之外的<div>情况以及选择包含在子内(或更深层嵌套)元素内的情况<div>.

实例:http://www.jsfiddle.net/timdown/XGSyn/

码:

function isOrContainsNode(ancestor, descendant) {
    var node = descendant;
    while (node) {
        if (node === ancestor) return true;
        node = node.parentNode;
    }
    return false;
}

function insertNodeOverSelection(node, containerNode) {
    var sel, range, html;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            if (isOrContainsNode(containerNode, range.commonAncestorContainer)) {
                range.deleteContents();
                range.insertNode(node);
            } else {
                containerNode.appendChild(node);
            }
        }
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        if (isOrContainsNode(containerNode, range.parentElement())) {
            html = (node.nodeType == 3) ? node.data : node.outerHTML;
            range.pasteHTML(html);
        } else {
            containerNode.appendChild(node);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)