我正在尝试在shadow-dom内部实现自定义文本编辑器功能。而且我需要在contenteditable div内获取当前光标位置。
我已经尝试了几种方法。但是他们都没有给出期望的输出。
答案 0 :(得分:0)
尝试为,
/*
style="-webkit-user-select:text;" is needed for iPad
*/
function getCaretCharacterOffsetWithin(element) {
var caretOffset = 0;
var doc = element.ownerDocument || element.document;
var win = doc.defaultView || doc.parentWindow;
var sel;
if (typeof win.getSelection != "undefined") {
sel = win.getSelection();
if (sel.rangeCount > 0) {
var range = win.getSelection().getRangeAt(0);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(element);
preCaretRange.setEnd(range.endContainer, range.endOffset);
caretOffset = preCaretRange.toString().length;
}
} else if ((sel = doc.selection) && sel.type != "Control") {
var textRange = sel.createRange();
var preCaretTextRange = doc.body.createTextRange();
preCaretTextRange.moveToElementText(element);
preCaretTextRange.setEndPoint("EndToEnd", textRange);
caretOffset = preCaretTextRange.text.length;
}
return caretOffset;
}
function getCaretPosition() {
if (window.getSelection && window.getSelection().getRangeAt) {
var range = window.getSelection().getRangeAt(0);
var selectedObj = window.getSelection();
var rangeCount = 0;
var childNodes = selectedObj.anchorNode.parentNode.childNodes;
for (var i = 0; i < childNodes.length; i++) {
if (childNodes[i] == selectedObj.anchorNode) {
break;
}
if (childNodes[i].outerHTML)
rangeCount += childNodes[i].outerHTML.length;
else if (childNodes[i].nodeType == 3) {
rangeCount += childNodes[i].textContent.length;
}
}
return range.startOffset + rangeCount;
}
return -1;
}
function showCaretPos(event) { // event parameter added
// This is the position object of pointer
var obj = {x : event.clientX,
y : event.clientY};
console.log(obj);
var el = document.getElementById("test");
var caretPosEl = document.getElementById("caretPos");
caretPosEl.innerHTML = "Caret position: " +
getCaretPosition();
getCaretCharacterOffsetWithin(el);
}
document.body.onkeyup = showCaretPos;
document.body.onmouseup = showCaretPos;
Non-editable text. Editable is below:
<div id="test" contenteditable="true" style="-webkit-user-select:text;">Hello, some <b>bold</b> and <i>italic and <b>bold</b></i> text</div>
<div id="caretPos"></div>
答案 1 :(得分:0)
使用ShadowRoot元素代替window.getSelection
,您需要将它作为getCaretPosition
的参数传递。假设您有getCaretPosition(shadowRoot)
,则代码将更改为shadowRoot.getSelection
。
有关ShadowRoot上可用的功能,请参见https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot。