使用Range.insertNode()动态地将图像添加到DOM

时间:2015-06-04 13:50:50

标签: javascript html html5 dom

如何使用Range.insertNode()动态地将IMG元素插入DOM?

我的HTML:

<div class="css_class_for_div" style="height: 250px;" contenteditable="true">
    <img src="/path/to/my/image/myimage.png" alt="/myimage.png" title="/myimage.png" class="css_class_for_image" e_resid="/myimage.png" />
    <br />
    <br />
    <span class="css_class_for_span"></span>
</div>
<input id="myButton" type="button" value="insert image" />

MY JS:

var button = document.getElementById("myButton");
button.addEventListener("click", function(e){
    var src = "/path/to/my/other/image/image2.png";
    var title = "/image2.png";
    var cssClassname = "css_class_for_image";
    var list = document.getElementsByClassName("css_class_for_div");
    var el = list[0];
    var selRanges = el.getSelection();
    if (selRanges.rangeCount > 0) {
        var curRange = selRanges.getRangeAt(0); // Range object
        if (curRange.toString().length == 0) {
            var imageNode = document.createElement('img');
            imageNode.src = src;
            imageNode.alt = title;
            imageNode.title = title;
            imageNode.className = cssClassname;
            curRange.insertNode(imageNode);
        }
    }
},false);

[Link to fiddle]

上述代码不起作用。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

如果您只是想使用Range.InsertNode()将Image2插入到classname = css_class_for_div的第一个div中,您可以使用以下代码。

我必须使用

var range = document.createRange();
range.selectNode(your div);
range.insertNode(your image);

Updated Fiddle

var button = document.getElementById("myButton");
button.addEventListener("click", function (e) {
    debugger;
    var range = document.createRange();
    var list = document.getElementsByClassName("css_class_for_div");
    if (list.length > 0) {
        var el = list[0];
        range.selectNode(el);
        var imageNode = getImageNode();
        range.insertNode(imageNode);
    }
}, false);

function getImageNode() {
    var src = "/path/to/my/other/image/image2.png";
    var title = "/image2.png";
    var cssClassname = "css_class_for_image";
    var imageNode = document.createElement('img');
    imageNode.src = src;
    imageNode.alt = title;
    imageNode.title = title;
    imageNode.className = cssClassname;
    return imageNode;
}