簡體   English   中英

在JavaScript中獲得錯誤的插入符位置

[英]Getting wrong caret position in javascript

從內容可編輯div內插入符號位置的上下文菜單中選擇后,我嘗試插入令牌。 如果插入符位置在一行中,我就可以做到這一點。

在我的情況下,每當出現其他HTML標記時(即當行更改時),范圍偏移值將設置為0。 我正在使用這兩個函數來獲取我在stackoverflow中某個地方找到的范圍。

任何幫助表示贊賞!

    function saveSelection() {
        var range = null;
        if (window.getSelection) {
            sel = window.getSelection();
            if (sel.getRangeAt && sel.rangeCount) {
               return sel.getRangeAt(0);
            }
        } else if (document.selection && document.selection.createRange) {
            return document.selection.createRange();
        }
        return null;
    }

我覺得這個問題是不是與內容系在你的元素無這是contenteditable 如前所述,因為您將上下文菜單與contenteditable div一起使用。 當您單擊上下文菜單時,它將獲得該上下文菜單的范圍值。

因此,在單擊某些菜單之前,應將范圍值存儲在某些變量中。

由於您的代碼不完整,因此我無法將任何示例與您的代碼聯系起來。

這是一個希望對您有幫助的示例:

 function pasteHtmlAtCaret(html) { 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 // non-standard and not supported in all 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); } range.insertNode(frag); // Preserve the selection if (lastNode) { range = range.cloneRange(); range.setStartAfter(lastNode); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } } } else if (document.selection && document.selection.type != "Control") { // IE < 9 document.selection.createRange().pasteHTML(html); } } 
 <input type="button" value="Paste HTML" onclick="document.getElementById('test').focus(); pasteHtmlAtCaret('<b>INSERTED</b>'); "> <div id="test" contenteditable="true"> Here is some nice text </div> 

上面提到的代碼的jsfiddle鏈接。

暫無
暫無

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

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