用户选择文本的持久标记

问题描述 投票:0回答:0

我试图让用户选择一段文本来执行命令。我一直在尝试围绕用户用鼠标突出显示的文本部分创建标记标签。如果用户选择其他文本,之前标记的文本应该恢复正常,新的文本应该变成标记。我还希望用户一次只能选择整个单词。我尝试的许多方法都失败了,因为(我认为)它无法处理非文本标签,例如
当我尝试使用多个标记标签而不是一个时,这使一切变得更加复杂。

解决这个问题的最佳方法是什么?

HTML:

<div id="editordiv" contenteditable>Some multiline text here<br>lines</div>

JS:

const editordiv = document.getElementById("editordiv")

document.addEventListener('selectionchange', handleSelectionChange);

function handleSelectionChange(e) {
  if (e.target.activeElement !== editordiv) return;
  const selection = window.getSelection() 
  const range = selection.getRangeAt(0);
  // tried lots of things here but couldn't get any to work

}

javascript html dom web-frontend
© www.soinside.com 2019 - 2024. All rights reserved.