[英]How to get the caret's position in contentEditable div when entering a new line?
I am making a rich text editor with UIWebview, which uses a contentEditable
div. 我正在使用UIWebview制作一个富文本编辑器,该编辑器使用contentEditable
div。 I want to get the caret's position in pixels. 我想获得插入符号的位置(以像素为单位)。 I have searched a lot, and I got the code below. 我已经搜索了很多,并且得到了下面的代码。
function getCaretClientPosition() {
var x = 0, y = 0;
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0);
if (range.getClientRects) {
var rects = range.getClientRects();
if (rects.length > 0) {
x = rects[0].left;
y = rects[0].top;
}
}
}
return { x: x, y: y };
}
The code above works well until I enter a newline. 上面的代码在输入换行符之前效果很好。 sel.getRangeAt(0)
returns null, so the function can't return the right caret Y pixels. sel.getRangeAt(0)
返回null,因此该函数无法返回右插入符号Y像素。
Here is the code I am using to get the caret's top position by inserting a temp object and remove it: 这是我用来通过插入临时对象并将其删除来获得插入符号最高位置的代码:
function getCaretTopPosition() {
document.execCommand('insertHTML', false, '<span id="hidden"></span>');
var hiddenNode = document.getElementById('hidden');
if (!hiddenNode) {
return 0;
}
var topPosition = hiddenNode.offsetTop;
hiddenNode.parentNode.removeChild(hiddenNode);
return topPosition;
}
This solution fixes the newLine issue in WebKit. 此解决方案解决了WebKit中的newLine问题。
function getCaretClientPosition() {
var x = 0, y = 0;
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0);
var needsToWorkAroundNewlineBug = (range.startContainer.nodeName.toLowerCase() == 'p'
&& range.startOffset == 0);
if (needsToWorkAroundNewlineBug) {
x = range.startContainer.offsetLeft;
y = range.startContainer.offsetTop;
} else {
if (range.getClientRects) {
var rects = range.getClientRects();
if (rects.length > 0) {
x = rects[0].left;
y = rects[0].top;
}
}
}
}
return { x: x, y: y };
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.