在包含标签的contenteditable div中获取插入符号索引 [英] Get caret index in contenteditable div including tags

查看:85
本文介绍了在包含标签的contenteditable div中获取插入符号索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 contentEditable div ,其中我有多个标签( br b u i )和文本。

I have a contentEditable div in which I have multiple tags (br, b, u, i) and text.

我需要获取相对于div的插入符号索引位置,包括所有标签。

I need to get the caret index position relative to the div, including all the tags.

<div id="h" contenteditable="true">abc<b>def<br>ghi</b>jkl</div>

如果光标在 g h ,我需要插入符号的索引位置为 14
问题是找到的方法使用 treeWalker 在这种情况下不起作用。
找不到粗体标签...可能是因为它没有关闭。
我也尝试了几种方法,但是还是没有运气。

If the cursor is between g and h, I need the caret index position to be 14. The problem is that the found methods that use a treeWalker do not work in this case. The bold tag is not found... probably because it isn't closed. Also I have tried several methods but still no luck.

我需要它在 Firefox 中工作。
谢谢。

I need it to work in Firefox. Thank you.

推荐答案

您尝试过吗?
获取相对于其父容器的范围的开始和结束偏移量

直接链接到jsfiddle:
https://jsfiddle.net/TjXEG/1/

Direct link to the jsfiddle: https://jsfiddle.net/TjXEG/1/

功能代码:

function getCaretCharacterOffsetWithin(element) {
    var caretOffset = 0;
    if (typeof window.getSelection != "undefined") {
        var range = window.getSelection().getRangeAt(0);
        var preCaretRange = range.cloneRange();
        preCaretRange.selectNodeContents(element);
        preCaretRange.setEnd(range.endContainer, range.endOffset);
        caretOffset = preCaretRange.toString().length;
    } else if (typeof document.selection != "undefined" && document.selection.type != "Control") {
        var textRange = document.selection.createRange();
        var preCaretTextRange = document.body.createTextRange();
        preCaretTextRange.moveToElementText(element);
        preCaretTextRange.setEndPoint("EndToEnd", textRange);
        caretOffset = preCaretTextRange.text.length;
    }
    return caretOffset;
}

function showCaretPos() {
    var el = document.getElementById("test");
    var caretPosEl = document.getElementById("caretPos");
    caretPosEl.innerHTML = "Caret position: " + getCaretCharacterOffsetWithin(el);
}

document.body.onkeyup = showCaretPos;
document.body.onmouseup = showCaretPos;

这篇关于在包含标签的contenteditable div中获取插入符号索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆