简体   繁体   English

在Javascript contenteditable div中插入文本

[英]Insert text in Javascript contenteditable div

I have a problem where I need to insert a text (string, may or may not have html tags) to a div. 我有一个问题,我需要在div中插入一个文本(字符串,可能有也可能没有html标签)。 It has to be a div and not a textarea. 它必须是一个div而不是textarea。

Is there anyway to do that? 反正有吗? First of all, I need to get the cursor position, then inserting the text in that position. 首先,我需要获取光标位置,然后将文本插入该位置。

It's similar to function insertAdjacentText, but it can only insert before or after a tag, and only works in IE. 它类似于函数insertAdjacentText,但它只能在标记之前或之后插入,并且只能在IE中使用。

Refer to this URL: http://yart.com.au/test/iframe.aspx . 请参阅此URL:http: //yart.com.au/test/iframe.aspx Note how you can position the cursor in the div, we need to add text at the cursor location. 注意如何将光标定位在div中,我们需要在光标位置添加文本。

If all you need to do is insert HTML at the current selection / insertion point, that is doable. 如果你需要做的只是在当前选择/插入点插入HTML,那是可行的。 Off the top of my head (to get you started): 脱离我的头脑(让你开始):

In IE, use document.selection.createRange().pasteHTML(theNewHTML). 在IE中,使用document.selection.createRange()。pasteHTML(theNewHTML)。

In other browsers, you should be able to use document.execCommand("InsertHTML", ...). 在其他浏览器中,您应该能够使用document.execCommand(“InsertHTML”,...)。

I've used these kinds of techniques only in editable iframes/documents, not divs, but these calls should work if the div is focused, I believe. 我只在可编辑的iframe /文档中使用了这些技术,而不是div,但是如果div是聚焦的话,这些调用应该有效,我相信。

As another answer warned, it gets ugly if you want finer-grained control, like inserting text in other places. 另一个答案警告说,如果你想要更细粒度的控制,就像在其他地方插入文字一样,它会变得很难看。

The Range and Selection Objects 范围和选择对象

Use the selection and range objects . 使用选择范围对象 These contain all kinds of information about the current selection, and where it lies within the node tree. 它们包含有关当前选择的各种信息,以及它在节点树中的位置。

Fair Warning: It's not entirely impossible to do what you're describing, but if you get very fancy, you'll be in pretty deep water of browser quirks and incompatibilities . 公平警告:做你所描述的事情并非完全不可能,但是如果你非常喜欢,你将陷入浏览器怪癖和不兼容的深层次。 You're going to have to do a lot of object detection , checking to make sure you've got consistent values and methods. 您将不得不进行大量的对象检测 ,检查以确保您拥有一致的值和方法。 Incrementally check all of your browsers as you develop. 在开发时逐步检查所有浏览器。 Good luck! 祝好运!

Here's a cross-browser example, adapted from this answer to work with iframes. 这是一个跨浏览器的示例,根据这个与iframe合作的答案进行了改编。

function pasteHtmlAtCaret(html, selectPastedContent, iframe) {
    var sel, range;
    var win = iframe ? iframe.contentWindow : window;
    var doc = win.document;
    if (win.getSelection) {
        // IE9 and non-IE
        sel = win.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 = doc.createElement("div");
            el.innerHTML = html;
            var frag = doc.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 = doc.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();
        }
    }
}

You can also use a round-about method using insertImage. 您还可以使用insertImage使用round-about方法。 You insert a fake image (or a small one) using the execCommand "insertImage", then you use Javascript to replace the innerHTML to add the text. 使用execCommand“insertImage”插入伪图像(或小图像),然后使用Javascript替换innerHTML以添加文本。

For example: 例如:

iFrame.focus()
iFrame.document.execCommand("insertImage", "", "fakeimage.jpg")
iFrame.document.body.innerHTML=iFrame.document.body.innerHTML.replace("<img src=\"fakeimage.jpg\">", "MY CUSTOM <b>HTML</b> HERE!")

Whereas iFrame is equal to the id of the intended iFrame. 而iFrame等于预期iFrame的id。 Or, you could use a DIV layer by using document.getElementById("IDofDIVlayer").innerHTML 或者,您可以使用document.getElementById(“IDofDIVlayer”)来使用DIV层.internalHTML

Be sure to focus before calling the execCommand, otherwise it may not work in IE. 在调用execCommand之前一定要集中注意力,否则它可能无法在IE中工作。

This method works in IE too. 此方法也适用于IE。 Tested. 测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM