gpt4 book ai didi

javascript - 获取内容可编辑插入符位置

转载 作者:行者123 更新时间:2023-11-28 03:36:00 27 4
gpt4 key购买 nike

我找到了大量关于如何在 contentEditable 元素中设置插入符位置的良好跨浏览器答案,但没有找到关于如何获取 首先是插入符号位置。

我想要做的是知道 keyup 上 div 中的插入符号位置。因此,当用户输入文本时,我可以随时知道 contentEditable 元素中的插入符位置。

<div id="contentBox" contentEditable="true"></div>

$('#contentbox').keyup(function() {
// ... ?
});

最佳答案

以下代码假设:

  • 可编辑的 <div> 中始终有一个文本节点并且没有其他节点
  • 可编辑 div 没有 CSS white-space属性设置为pre

如果您需要一种更通用的方法来处理嵌套元素的内容,请尝试以下答案:

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>

关于javascript - 获取内容可编辑插入符位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57738299/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com