更改可编辑 div 中所选单词的颜色并撤消它

问题描述

以下代码运行良好,但只有一次。我已经复制了两次以再次更改颜色。但是这个词仍然没有反应。是否有针对此问题的非 jQuery 解决方案?

function red() {
  var selection = window.getSelection().getRangeAt(0);
  if (window.getSelection().baseNode.parentNode.id != "foo") return;
  var selectedText = selection.extractContents();
  var span = document.createElement("span");
  span.style.color = "red";
  span.appendChild(selectedText);
  selection.insertNode(span);
}

function blue() {
  var selection = window.getSelection().getRangeAt(0);
  if (window.getSelection().baseNode.parentNode.id != "foo") return;
  var selectedText = selection.extractContents();
  var span = document.createElement("span");
  span.style.color = "blue";
  span.appendChild(selectedText);
  selection.insertNode(span);
}
<button onclick="red()">Click to make highlighted text red.</button>
<button onclick="blue()">Click to make highlighted text blue.</button>
<div id="foo" style="width:30em; height:30em; border-style:solid; border-color:black;" contenteditable="true"></div>

Reference
Fiddle

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)