簡體   English   中英

Javascript:在WYSIWYG編輯器中將文本粘貼到插入符號

[英]Javascript: Pasting text at caret in WYSIWYG editor

在JavaScript方面我還在學習繩索,其中一個導致我最大問題的問題是理解插入位置。 目前我正在為wiki編寫一個參考表單( http://t3chbox.wikia.com/wiki/MediaWiki:Wikia.js/referenceForm.js )並讓它為wiki的源代碼編輯器工作,但不是WYSIWYG編輯器(Visual Editor)。 我想知道這里是否有人知道如何獲得插入位置,然后粘貼編輯內容所在的iframe的文本?

WYSIWYG編輯器可以在這里看到: http//t3chbox.wikia.com/wiki/Test?action =編輯(編輯雖然沒有登錄那些有Wikia帳戶並且Visual設置為關閉)。 我一直在使用獲取內容並嘗試粘貼在插入符號的方法是這樣的:

$(document.getElementById('cke_contents_wpTextbox1').getElementsByTagName('iframe')[0].contentDocument.body).insertAtCaret('hello');

謝謝 :)

您使用的jquery insertAtCaret函數僅適用於textareas和輸入字段。 它不適用於contentEditable元素。 您可以查看此jsfiddle,以便在插入符號中插入contentEditable元素。

    function pasteHtmlAtCaret(html,windo) {
        windo = windo || window;
        var sel, range;
        if (windo.getSelection) {
            // IE9 and non-IE
            sel = windo.getSelection();
            console.log(sel);
            if (sel.getRangeAt && sel.rangeCount) {
                range = sel.getRangeAt(0);
                console.log(range);
                range.deleteContents();

                // Range.createContextualFragment() would be useful here but is
                // non-standard and not supported in all browsers (IE9, for one)
                var el = windo.document.createElement("div");
                el.innerHTML = html;
                var frag = windo.document.createDocumentFragment(), node, lastNode;
                while ( (node = el.firstChild) ) {
                    lastNode = frag.appendChild(node);
                }
                range.insertNode(frag);

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

//usage
    var iframeWindow = document.getElementById('cke_contents_wpTextbox1').getElementsByTagName('iframe')[0].contentWindow;
    pasteHtmlAtCaret("Hello World!",iframeWindow);

http://jsfiddle.net/jwvha/534/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM