问题描述
我有一个 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
。
问题是找到的方法使用在这种情况下不起作用。
找不到粗体标签...可能是因为它没有关闭。
我也尝试了几种方法,但是还是没有运气。
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:
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中获取插入符号索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!