【问题标题】:How do I keep an onInput event from being triggered when using document.execCommand()?使用 document.execCommand() 时如何防止触发 onInput 事件?
【发布时间】:2021-02-14 04:57:12
【问题描述】:

我有一个div,用户可以通过contenteditable 属性编辑其内容。当用户在 div 中键入内容时,会调用一个函数。我正在使用oninput 事件来触发该功能,因为onkeydown 不适用于该功能应该做的一些事情。

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

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

这是我的代码:

注意:对于这个例子,我简化了触发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>

【问题讨论】:

    标签: javascript input contenteditable execcommand


    【解决方案1】:

    我在函数中添加了一个 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.
      }
    }

    【讨论】:

      猜你喜欢
      • 2020-11-21
      • 2010-10-27
      • 1970-01-01
      • 2015-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多