我想使用 window.getSelection 制作一个具有大胆功能的 HTML 文本编辑器

I want to make a HTML text editor having bold functionality using window.getSelection

它使整个文本加粗。我只希望选定的文本变粗(严格禁止执行命令)

let boldBtn = document.getElementById('Bold-Btn');
let boldClickListener = (event) =>
{
    event.preventDefault();
    let selection = window.getSelection();
    let final = `<span class="text-bold">${selection.focusNode.textContent}</span>`;
    selection.anchorNode.parentElement.innerHTML=final;
    console.log(selection);
};

boldBtn.addEventListener('click',boldClickListener);

执行此操作的一种方法可能是执行以下操作:

  • 获取 window 选项。
  • 将所选内容转换为字符串以获取文本。
  • 创建将成为粗体的元素。
  • parentElementinnerHTML 中包含的选定文本替换为粗体元素。

基于您提供的代码的示例:

let boldBtn = document.getElementById('Bold-Btn');
let boldClickListener = (event) => {
  event.preventDefault();
  // Get selection
  let selection = window.getSelection();
  // Get string of text from selection
  let text = selection.toString();
  // Create bolded element that will replace the selected text
  let final = `<span class="text-bold">${text}</span>`;
  // Replace the selected text with the bolded element
  selection.anchorNode.parentElement.innerHTML = selection.anchorNode.parentElement.innerHTML.replace(text, final);
};

boldBtn.addEventListener('click', boldClickListener);
.text-bold {
  font-weight: bold;
}
<div>
Test this text
</div>
<button id="Bold-Btn">
Bold
</button>

请注意,如果任何现有文本已经是粗体,您可能希望在创建粗体元素时添加更多逻辑。