Как установить каретку на узел в элементе contenteditable


Секрет

Вы НЕ МОЖЕТЕ установить каретку на contenteditable элемент только с помощью foucs() на элементе.

Пример кода

JavaScript

const setCaret = (
  contenteditableElement,
  node,
  position
) => {
  const selection = window.getSelection();
  if (!selection) return;

  // Create a new range
  const range = document.createRange();
  range.setStart(node, position);
  range.collapse(true);

  // Remove the current range
  selection.removeAllRanges();

  // Add the new range
  selection.addRange(range);

  // Focus on the contenteditable element instead of the node if needed.
  contenteditableElement.focus();
};
Вход в полноэкранный режим Выход из полноэкранного режима

TypeScript

const setCaret = (
  contenteditableElement: HTMLElement,
  node: Node,
  position: number
): void => {
  const selection = window.getSelection();
  if (!selection) return;

  // Create a new range
  const range = document.createRange();
  range.setStart(node, position);
  range.collapse(true);

  // Remove the current range
  selection.removeAllRanges();

  // Add the new range
  selection.addRange(range);

  // Focus on the contenteditable element instead of the node if needed.
  contenteditableElement.focus();
};
Вход в полноэкранный режим Выйти из полноэкранного режима

Деталь

range.collapse(true);
Ввести полноэкранный режим Выход из полноэкранного режима

устанавливает Range.collapsed в true, что означает, что начальная и конечная точки диапазона находятся в одном и том же положении.

Ссылки

  • Выбор
  • Window.getSelection()
  • Document.createRange()
  • Range.collapsed
  • Range.collapse()
  • Range.setStart()
  • Selection.removeAllRanges()
  • Selection.addRange()
  • HTMLElement.focus()

Оцените статью
devanswers.ru
Добавить комментарий