【问题标题】:How to set the cursor position in a contenteditable div in react如何在 React 中的可编辑的 div 中设置光标位置
【发布时间】:2023-01-10 17:12:21
【问题描述】:

我正在尝试创建一个文本编辑器,我正在使用 contenteditable div,每次有人更改其中的文本时,我想用 strong 元素包装所有新文本并更改 div 的 innerHTML

这是我尝试过的(我正在使用 react/nextjs)

使用效果(()=> { 如果(!divRef.current)返回;

let text = divRef.current.innerText;
const htmlArray = text.split(" ").map((word) => {
  return `<strong style="color: red">${word} </strong>`;
});
text = htmlArray.join("");
divRef.current.innerHTML = text;

}, [文本]);

这里的一切都按预期工作,但每次我键入一个字符时,光标都会转到开头,文本会向后呈现。如何解决我希望光标在用户键入时停留在 div 末尾的问题

【问题讨论】:

标签: javascript html reactjs typescript contenteditable


【解决方案1】:

这是因为每次 text 更改时,您都在更新 contenteditable div 的 innerHTML。

您需要捕获实际位置,并在使用 Selection 更改状态后将其设置回去

useEffect(() => {
  if (!divRef.current) return;

  // Get the current cursor position
  let selection = window.getSelection();
  let range = selection.getRangeAt(0);
  let cursorPosition = range.startOffset;

  // Update the innerHTML
  let text = divRef.current.innerText;
  const htmlArray = text.split(" ").map((word) => {
    return `<strong data-id="hey" style="color: red">${word} </strong>`;
  });
  text = htmlArray.join("");
  divRef.current.innerHTML = text;

  // Get the new cursor position
  selection = window.getSelection();
  range = selection.getRangeAt(0);

  // Set the cursor position to the new position
  range.setStart(range.startContainer, cursorPosition);
  range.collapse(true);
  selection.removeAllRanges();
  selection.addRange(range);
}, [text]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    • 2011-01-13
    • 2016-01-28
    • 1970-01-01
    • 2014-02-14
    • 2016-07-05
    相关资源
    最近更新 更多