在contentEditable div中的插入位置添加内容

时间:2015-03-25 07:07:03

标签: javascript jquery html contenteditable caret

我正在尝试在可编辑div中的插入位置添加内容。

<div class="pull-left text-center">
    <a class="dropdown-toggle" data-toggle="dropdown" id="content1" href="#">Simple
    </a>
</div>
<div class="pull-left text-center">
    <a class="dropdown-toggle" data-toggle="dropdown" href="#">MouseOver </a>
    <ul class="dropdown-menu">
        <li>
            <div onclick="AddContent()">
                Add</div>
        </li>
    </ul>
</div>
<div id="form" contenteditable="true" style="height: 500px;">
</div>


<script type="text/javascript">

    $('#content1').click(function () {
        $('#form').focus();
        pasteHtmlAtCaret('<b>ABCD</b>', false);
    });

    function AddContent() {
        document.getElementById('form').focus();
        pasteHtmlAtCaret('<b>ABCD</b>', false);
    }


    function pasteHtmlAtCaret(html, selectPastedContent) {
        var sel, range;
        if (window.getSelection) {
            // IE9 and non-IE
            sel = window.getSelection();
            if (sel.getRangeAt && sel.rangeCount) {

                range = sel.getRangeAt(0);
                range.deleteContents();

                // Range.createContextualFragment() would be useful here but is
                // only relatively recently standardized and is not supported in
                // some browsers (IE9, for one)
                var el = document.createElement("div");
                el.innerHTML = html;
                var frag = document.createDocumentFragment(), node, lastNode;
                while ((node = el.firstChild)) {
                    lastNode = frag.appendChild(node);
                }
                var firstNode = frag.firstChild;
                range.insertNode(frag);

                // Preserve the selection
                if (lastNode) {
                    range = range.cloneRange();
                    range.setStartAfter(lastNode);
                    if (selectPastedContent) {
                        range.setStartBefore(firstNode);
                    } else {
                        range.collapse(true);
                    }
                    sel.removeAllRanges();
                    sel.addRange(range);
                }
            }
        } else if ((sel = document.selection) && sel.type != "Control") {
            // IE < 9

            var originalRange = sel.createRange();
            originalRange.collapse(true);
            sel.createRange().pasteHTML(html);
            if (selectPastedContent) {
                range = sel.createRange();
                range.setEndPoint("StartToStart", originalRange);
                range.select();
            }
        }
    }
</script>

点击Simple,它会在插入位置添加内容,这很好,但是当我每次在文档的起始位置添加内容时点击Add。我该怎么做呢?感谢。

0 个答案:

没有答案