使用document.execCommand时如何避免触发onInput事件?

问题描述

我有一个div,用户可以通过contenteditable属性对其内容进行编辑。当用户在div中键入内容时,将调用一个函数。我正在使用oninput事件来触发该功能,因为onkeydown无法使用该功能应该执行的某些工作。

我还有粗体,斜体和下划线按钮,允许用户通过document.execCommand()相应地设置文本样式。

我的问题:当用户使用按钮设置文本样式时,不应触发oninput触发的功能。但这就是正在发生的事情。有什么办法可以防止它?

这是我的代码:

注意:对于此示例,我简化了在输入时触发的函数。实际上,它所做的不仅仅是改变元素的innerHTML

JSFiddle

document.getElementById("editableDiv").focus();

function boldText () {
    document.execCommand("bold");
}

function myFunction () {
    document.getElementById("feedback").innerHTML="The content was changed."
}
body {
  padding: 10px;
  font-family: sans-serif;
}

input {
  padding: 5px;
  outline: 0;
  font-weight: bold;
}

div {
  margin: 10px 0;
  width: 200px;
  border: solid 1px #000;
  padding: 5px;
}
<input type="button" value="Bold" onclick="boldText();">

<div id="editableDiv" contenteditable="true" spellcheck="false" oninput="myFunction();">
  Hello,World!
</div>

<p id="feedback"></p>

解决方法

我在函数中添加了一个If语句,使其仅在event.inputType != "formatBold"时起作用:

function myFunction() {
  if (event.inputType == "formatBold") {
    document.getElementById("feedback").innerHTML = "The text was stylized.";
  } else {
    document.getElementById("feedback").innerHTML = "The content was changed.";
    // + other things the function is supposed to do.
  }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...