简体   繁体   English

在JavaScript中获得错误的插入符位置

[英]Getting wrong caret position in javascript

I am trying to insert token after selecting from context menu at the caret position inside a contenteditable div. 从内容可编辑div内插入符号位置的上下文菜单中选择后,我尝试插入令牌。 I have managed to do that if the caret position is in a single line. 如果插入符位置在一行中,我就可以做到这一点。

In my case the range offset value will set to 0 whenever other HTML tags appear ie when the line changes. 在我的情况下,每当出现其他HTML标记时(即当行更改时),范围偏移值将设置为0。 I am using these two functions for getting the range which I've found somewhere in stackoverflow. 我正在使用这两个函数来获取我在stackoverflow中某个地方找到的范围。

Any help is appreciated! 任何帮助表示赞赏!

    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;
    }

I think the problem is not with the no of line of content in your element which is contenteditable . 我觉得这个问题是不是与内容系在你的元素无这是contenteditable Because you are using context menu with contenteditable div as you have mentioned. 如前所述,因为您将上下文菜单与contenteditable div一起使用。 And when ever you click on the context menu it will get range value of that context menu. 当您单击上下文菜单时,它将获得该上下文菜单的范围值。

So you should store the range value on certain variable before clicking on certain menu. 因此,在单击某些菜单之前,应将范围值存储在某些变量中。

Since your code is incomplete I cannot relate any example with your code. 由于您的代码不完整,因此我无法将任何示例与您的代码联系起来。

Here is one example hope this will help you: 这是一个希望对您有帮助的示例:

 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 link for the above mentioned code. 上面提到的代码的jsfiddle链接。

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

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