使用 Window.getSelection() 将所选文本加粗/取消加粗

Big*_*ros 3 html javascript css

我正在尝试制作一个简单的文本编辑器,以便用户能够将选定的文本加粗/取消加粗。我想用Window.getSelection()Document.execCommand()。它完全符合我的要求,但是当您将任何文本加粗时,您无法将其取消粗体。我希望它能够加粗和取消加粗任何选定的文本。我尝试了几件事但没有成功。

function addBold(){
const selection = window.getSelection().getRangeAt(0);
const selectedText = selection.extractContents();
const span = document.createElement("span");
span.classList.toggle("bold-span");
span.appendChild(selectedText);
selection.insertNode(span);
};
Run Code Online (Sandbox Code Playgroud)
.bold-span {font-weight: bold;}
Run Code Online (Sandbox Code Playgroud)
<p contentEditable>Bold anything here and unbold it</p>
<button onclick="addBold()">Bold</button>
Run Code Online (Sandbox Code Playgroud)

小智 6

这与您想要的很接近,但是将单词组合在一起,因此取消选择将从整个单词中删除。我无法完成此任务,因为我必须离开,但这应该是一个很好的起点。

function addBold(){
  const selection = window.getSelection().getRangeAt(0);
  
  let selectedParent = selection.commonAncestorContainer.parentElement;
  
  //console.log(parent.classList.contains("bold-span"))
  //console.log(parent)
  let mainParent = selectedParent;
  if(selectedParent.classList.contains("bold-span"))
  {
    var text = document.createTextNode(selectedParent.textContent);
    mainParent = selectedParent.parentElement;
    mainParent.insertBefore(text, selectedParent);
    mainParent.removeChild(selectedParent);
    mainParent.normalize();
  }
  else
  {
    const span = document.createElement("span");
    span.classList.toggle("bold-span");
    span.appendChild(selection.extractContents());
    //selection.surroundContents(span);
    selection.insertNode(span);
    mainParent.normalize();
  }
  
  //selection is set to body after clicking button for some reason
  //https://stackoverflow.com/questions/3169786/clear-text-selection-with-javascript
  if (window.getSelection) {
    if (window.getSelection().empty) {  // Chrome
      window.getSelection().empty();
    } else if (window.getSelection().removeAllRanges) {  // Firefox
      window.getSelection().removeAllRanges();
    }
  } else if (document.selection) {  // IE?
    document.selection.empty();
  }

};
Run Code Online (Sandbox Code Playgroud)
.bold-span {font-weight: bold;}
Run Code Online (Sandbox Code Playgroud)
<p contentEditable>Bold anything here and unbold it</p>
<button onclick="addBold()">Bold</button>
Run Code Online (Sandbox Code Playgroud)