获取contentEditable插入符号索引位置 [英] Get contentEditable caret index position
问题描述
关于如何在 contentEditable
元素中设置光标或插入符号索引位置,我发现了很多很好的,跨浏览器的答案,但是没有关于如何获取或查找其光标的问题。索引...
I'm finding tons of good, crossbrowser anwers on how to SET the cursor or caret index position in a contentEditable
element, but none on how to GET or find its index...
我想做的是知道此div中插入符号的索引,位于 keyup
。
What I want to do is know the index of the caret within this div, on keyup
.
因此,当用户键入文本时,我随时可以知道其光标在 contentEditable
元素内的索引。
So, when the user is typing text, I can at any point know its cursor's index within the contentEditable
element.
编辑:我在div内容(文本)中寻找 INDEX ,而不是光标坐标。
I'm looking for the INDEX within the div contents (text), not the cursor coordinates.
<div id="contentBox" contentEditable="true"></div>
$('#contentbox').keyup(function() {
// ... ?
});
推荐答案
以下代码假定:
- 可编辑的
< div>
中始终只有一个文本节点,没有其他节点 - 可编辑div没有将CSS
空白
属性设置为pre
- There is always a single text node within the editable
<div>
and no other nodes - The editable div does not have the CSS
white-space
property set topre
如果您需要更通用的方法来处理带有嵌套元素的内容,请尝试以下答案:
If you need a more general approach that will work content with nested elements, try this answer:
https://stackoverflow.com/a/4812022/96100
代码:
function getCaretPosition(editableDiv) {
var caretPos = 0,
sel, range;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0);
if (range.commonAncestorContainer.parentNode == editableDiv) {
caretPos = range.endOffset;
}
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
if (range.parentElement() == editableDiv) {
var tempEl = document.createElement("span");
editableDiv.insertBefore(tempEl, editableDiv.firstChild);
var tempRange = range.duplicate();
tempRange.moveToElementText(tempEl);
tempRange.setEndPoint("EndToEnd", range);
caretPos = tempRange.text.length;
}
}
return caretPos;
}
#caretposition {
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="contentbox" contenteditable="true">Click me and move cursor with keys or mouse</div>
<div id="caretposition">0</div>
<script>
var update = function() {
$('#caretposition').html(getCaretPosition(this));
};
$('#contentbox').on("mousedown mouseup keydown keyup", update);
</script>
这篇关于获取contentEditable插入符号索引位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!