禁用 contenteditable 属性后如何取消拼写错误单词的高亮显示

4

var editBtn = document.querySelector("button#edit"),
  editable = editBtn.previousElementSibling,
  saveBtn = editBtn.nextElementSibling;

editBtn.addEventListener('click', startEdit, false);
saveBtn.addEventListener('click', endEdit, false);

function startEdit() {
  editable.setAttribute("contenteditable", true);
  editable.focus();
}

function endEdit() {
  editable.setAttribute("contenteditable", false);
  // even tried
  // editable.removeAttribute("contenteditable");
}
body {
  background-color: #ccc;
}
p[contenteditable="true"] {
  font-family: "Arial", "Georgia", "Calibri";
  background-color: #fff;
  font-size: 14px;
  padding: 4px;
  color: #424245;
  border: 1px solid #C7C6CD;
}
<p>click edit, type some mispelled words, click save and highlighting remains</p>
<button id="edit">edit</button>
<button>save</button>

当点击编辑按钮时,我的特性应用程序会设置 <p></p> 元素上的 contenteditable="true",然后在按下 ENTER 键时将其设置为 false

现在,在按下 ENTER 键并将 contenteditable="false" 设置为元素后,即使现在该元素不再可编辑,所有未拼写正确的单词仍然保持高亮显示。

是否有一种方法来在这种情况下取消拼写错误单词的高亮显示。

我在编辑器中运行代码片段时遇到问题,如果有任何问题,请告诉我。


1
https://dev59.com/Smw15IYBdhLWcg3whME1 - Alessandro Scarlatti
1个回答

1
最简单的方法可能就是用原内容覆盖自身:
var html = editable.innerHTML;
editable.innerHTML = "";
editable.innerHTML = html;

清空内容是必要的,但遗憾的是,仅使用editable.innerHTML = editable.innerHTML;似乎无效。

var editBtn = document.querySelector("button#edit"),
    editable = editBtn.previousElementSibling,
    saveBtn = editBtn.nextElementSibling;

editBtn.addEventListener('click', startEdit, false);
saveBtn.addEventListener('click', endEdit, false);

function startEdit() {
  editable.setAttribute("contenteditable", true);
  editable.focus();
}

function endEdit() {
  editable.setAttribute("contenteditable", false);
  var html = editable.innerHTML;
  editable.innerHTML = "";
  editable.innerHTML = html;
}
body {
  background-color: #ccc;
}
p[contenteditable="true"] {
  font-family: "Arial", "Georgia", "Calibri";
  background-color: #fff;
  font-size: 14px;
  padding: 4px;
  color: #424245;
  border: 1px solid #C7C6CD;
}
<p>click edit, type some mispelled words, click save and highlighting remains</p>
<button id="edit">edit</button>
<button>save</button>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接