【发布时间】:2021-02-14 04:57:12
【问题描述】:
我有一个div,用户可以通过contenteditable 属性编辑其内容。当用户在 div 中键入内容时,会调用一个函数。我正在使用oninput 事件来触发该功能,因为onkeydown 不适用于该功能应该做的一些事情。
我还有粗体、斜体和下划线按钮,允许用户通过document.execCommand() 相应地设置文本样式。
我的问题:当用户使用按钮设置文本样式时,不应触发 oninput 触发的功能。但这就是正在发生的事情。有什么办法可以预防吗?
这是我的代码:
注意:对于这个例子,我简化了触发oninput的函数。实际上,它所做的不仅仅是改变元素的innerHTML。
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