如何在使用execCommand插入后获取图像元素?

Naj*_*zak 8 javascript html5 contenteditable execcommand insert-image

在使用execCommand插入图像后,有没有办法获取图像元素?例如

e.execCommand('insertimage',0,'ronaldo.png')
Run Code Online (Sandbox Code Playgroud)

Ker*_*mes 11

不要使用insertimage,使用普通旧的,insertHTML并给你插入ID的元素,以便以后可以引用它.即

function insertHTML(img) {
  var id = "rand" + Math.random();
  var doc = document.getElementById("editor");
  doc = doc.document ? doc.document : doc.contentWindow.document;
  img = "<img src='" + img + "' id=" + id + ">";

  if(document.all) {
    var range = doc.selection.createRange();
    range.pasteHTML(img);
    range.collapse(false);
    range.select();
  } else {
    doc.execCommand("insertHTML", false, img);
  }
  return doc.getElementById(id);
};
Run Code Online (Sandbox Code Playgroud)


Tim*_*own 6

您可以使用浏览器在插入的图像之后立即放置插入符并从那里返回的事实.以下需要DOM范围和选择支持,它排除IE <= 8,但如果这很重要,那么你可以使用像我自己的Rangy这样的库来填补这个空白.

演示:http://jsfiddle.net/xJkuj/

码:

function previousNode(node) {
    var previous = node.previousSibling;
    if (previous) {
        node = previous;
        while (node.hasChildNodes()) {
            node = node.lastChild;
        }
        return node;
    }
    var parent = node.parentNode;
    if (parent && parent.nodeType.hasChildNodes()) {
        return parent;
    }
    return null;
}

document.execCommand("InsertImage", false, "http://placekitten.com/200/300");

// Get the current selection
var sel = window.getSelection();
if (sel.rangeCount > 0) {
    var range = sel.getRangeAt(0);
    var node = range.startContainer;
    if (node.hasChildNodes() && range.startOffset > 0) {
        node = node.childNodes[range.startOffset - 1];
    }

    // Walk backwards through the DOM until we find an image
    while (node) {
        if (node.nodeType == 1 && node.tagName.toLowerCase()  == "img") {
            alert("Found inserted image with src " + node.src);
            break;
        }
        node = previousNode(node);
    }
}
Run Code Online (Sandbox Code Playgroud)