作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我找到了大量关于如何在 contentEditable
元素中设置插入符位置的良好跨浏览器答案,但没有找到关于如何获取 首先是插入符号位置。
我想要做的是知道 keyup
上 div 中的插入符号位置。因此,当用户输入文本时,我可以随时知道 contentEditable
元素中的插入符位置。
<div id="contentBox" contentEditable="true"></div>
$('#contentbox').keyup(function() {
// ... ?
});
最佳答案
以下代码假设:
<div>
中始终有一个文本节点并且没有其他节点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/
我是一名优秀的程序员,十分优秀!