Учитывая узел абзаца, как ниже < /p>
Код: Выделить всё
Node 1
Node 2
Node 3
Node 4
Node 5
< /code>
Я хочу иметь возможность установить позицию курсора в конце узла 5, чтобы сделать это, я сделал следующее ниже. < /p>
//function to sum the length of the the #text node text content
function sumAllTextNodeLengthInTreeAsOffset(tree: HTMLElement, childNodeIndex?: number | undefined) {
let sum = 0;
for(let i=0; i
Тогда я использую функцию ниже, чтобы установить положение курсора < /p>
function setCursorPositionInContenteditableElement(el: HTMLElement, pos: number) {
const
selectedText = window.getSelection(),
selectedRange = document.createRange()
;
if(el.childNodes[0]) {
selectedRange.setStart(el.childNodes[0], pos);
}
else {
el.innerText = ' ';
selectedRange.setStart(el.childNodes[0], pos);
const time = setTimeout(() => {
el.innerText = '';
clearTimeout(time);
}, 0);
}
selectedRange.collapse(true);
selectedText?.removeAllRanges();
selectedText?.addRange(selectedRange);
el.focus();
}
< /code>
Если последний узел дочернего узела #Text Node, то установите позицию курсора на конец последнего ребенка ниже, всегда терпит неудачу, вместо того, чтобы устанавливать позицию курсора для последнего ребенка, он устанавливает позицию курсора на первый ребенок. < /p>
if((tree as HTMLElement).hasChildNodes()) {
if(
(
(tree as HTMLElement).childNodes[
(tree as HTMLElement).childNodes.length - 1
] as HTMLElement
).nodeType === 3
) {
setCursorPositionInContenteditableElement(
(tree as HTMLElement),
(tree as HTMLElement).children.length >= 1?
((tree as HTMLElement).childNodes.length - 1)
:
sumAllTextNodeLengthInTreeAsOffset(tree as HTMLElement)
);
(tree as HTMLElement).focus();
(tree as HTMLElement).click();
}
}
Я пытаюсь сделать следующее < /p>
setCursorPositionInContenteditableElement(p, )
and the index of the last child from the image below is 10. instead of setting the cursor position at the end of at node 10, the cursor is set at offset 10 of the first child of paragraph tag.
< /code>
Я попытался подвести итог всей длины содержимого текста текстового узла до последней длины текста дочернего текста для расчета смещения последнего ребенка, который является текстовым узлом, но установление расчетного смещения причина Ошибка.
Пожалуйста, кто -нибудь может помочь мне, как решить эту проблему.
Подробнее здесь: https://stackoverflow.com/questions/794 ... agraph-tag
Мобильная версия