Spec-Zone.ru › Web APIs

EditContext: свойство selectionEnd

Ограниченная доступность

Эта функция не является базовой, так как она не работает в некоторых из наиболее широко используемых браузеров.

  • Узнать больше
  • Посмотреть полную совместимость
  • Отправить отзыв

Экспериментальный: Это экспериментальная технология.
Перед использованием в производстве внимательно проверьте таблицу совместимости с браузерами.

Чтение-только свойство selectionEnd объекта EditContext указывает на смещение конца текущего выделенного фрагмента текста в редактируемом содержимом.

Значение

Число Number

Примеры

Использование selectionEnd для отрисовки выделения пользователя в редактируемой области рисования

Этот пример демонстрирует, как использовать свойства selectionStart и selectionEnd для отрисовки текущего выделения в элементе <canvas>, связанном с объектом EditContext.

<canvas id="editor-canvas"></canvas>
const ANCHOR_X = 10;
const ANCHOR_Y = 30;
const FONT_SIZE = 20;

const canvas = document.getElementById("editor-canvas");
const ctx = canvas.getContext("2d");
ctx.font = `${FONT_SIZE}px Arial`;

const editContext = new EditContext({
  text: "Hello world!",
  selectionStart: 6,
  selectionEnd: 11,
});
canvas.editContext = editContext;

function render() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Render the entire text content first.
  ctx.fillStyle = "black";
  ctx.fillText(editContext.text, ANCHOR_X, ANCHOR_Y);

  // Get the width from the start of the text to the start of the selection.
  const selectionStartX = ctx.measureText(
    editContext.text.substring(0, editContext.selectionStart),
  );

  // Get the width of the selection.
  const selectionWidth = ctx.measureText(
    editContext.text.substring(
      editContext.selectionStart,
      editContext.selectionEnd,
    ),
  );

  // Draw a rectangle on top of the text to represent the selection.
  ctx.fillStyle = "blue";
  ctx.fillRect(
    selectionStartX.width + ANCHOR_X,
    ANCHOR_Y - FONT_SIZE,
    selectionWidth.width,
    FONT_SIZE,
  );

  // Re-render just the selected text in white, over the rectangle.
  ctx.fillStyle = "white";
  ctx.fillText(
    editContext.text.substring(
      editContext.selectionStart,
      editContext.selectionEnd,
    ),
    selectionStartX.width + ANCHOR_X,
    ANCHOR_Y,
  );
}

render();

Спецификации

Спецификация
API EditContext
# dom-editcontextinit-selectionend

Совместимость с браузерами

Рабочие столы Мобильные устройства
Chrome Edge Firefox Opera Safari Chrome Android Firefox для Android Opera Android Safari на iOS Samsung Internet WebView Android
selectionEnd 121 121 Нет 107 Нет 121 Нет 81 Нет 25.0 121

© 2005–2024 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/EditContext/selectionEnd

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API