如何解决使用document.execCommand时如何避免触发onInput事件?
我有一个div
,用户可以通过contenteditable
属性对其内容进行编辑。当用户在div中键入内容时,将调用一个函数。我正在使用oninput
事件来触发该功能,因为onkeydown
无法使用该功能应该执行的某些工作。
我还有粗体,斜体和下划线按钮,允许用户通过document.execCommand()
相应地设置文本样式。
我的问题:当用户使用按钮设置文本样式时,不应触发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>
解决方法
我在函数中添加了一个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.
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。