簡體   English   中英

如何在 React 中的 contenteditable div 中設置 cursor position

[英]How to set the cursor position in a contenteditable div in react

我正在嘗試創建一個文本編輯器,並且我正在使用一個contenteditable div,每次有人更改其中的文本時,我都想用strong元素包裝所有新文本並更改 div 的 innerHTML

這是我嘗試過的(我正在使用 react/nextjs)

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

    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;
  }, [text]);

這里的一切都按預期工作,但每次我鍵入一個字符時,cursor 都會轉到開頭,文本會向后呈現。 如何解決我希望 cursor 在用戶鍵入時保留在 div 末尾的問題

這是因為每次text更改時您都在更新 contenteditable div 的 innerHTML。

您需要捕獲實際的position,並在state隨Selection更改后重新設置

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

  // Get the current cursor position
  let selection = window.getSelection();
  if (!selection.rangeCount) return;
  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]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM