内容可编辑的更改事件
2022-08-29 23:16:39
我想在用户编辑 with 属性的内容时运行函数。什么等同于事件?div
contenteditable
onchange
我正在使用jQuery,因此任何使用jQuery的解决方案都是首选。谢谢!
我想在用户编辑 with 属性的内容时运行函数。什么等同于事件?div
contenteditable
onchange
我正在使用jQuery,因此任何使用jQuery的解决方案都是首选。谢谢!
正如评论中指出的那样,这并没有回答所提出的问题,这个问题想要与事件等效而不是事件。但是,我将按原样保留在此处。change
input
我建议将侦听器附加到由可编辑元素触发的关键事件,尽管您需要注意,并且在内容本身更改之前触发事件。这不会涵盖更改内容的所有可能方法:用户还可以使用“编辑”或上下文浏览器菜单中的剪切,复制和粘贴,因此您可能也希望处理和事件。此外,用户可以删除文本或其他内容,因此那里有更多事件(例如)。您可能希望轮询元素的内容作为回退。keydown
keypress
cut
copy
paste
mouseup
2014年10月29日更新
从长远来看,HTML5输入
事件就是答案。在撰写本文时,当前Mozilla(来自Firefox 14)和WebKit / Blink浏览器中的元素都支持它,但不支持IE。contenteditable
演示:
document.getElementById("editor").addEventListener("input", function() {
console.log("input event fired");
}, false);
<div contenteditable="true" id="editor">Please type something in here</div>
这是一个更有效的版本,用于所有内容可编辑。它基于这里最重要的答案。on
$('body').on('focus', '[contenteditable]', function() {
const $this = $(this);
$this.data('before', $this.html());
}).on('blur keyup paste input', '[contenteditable]', function() {
const $this = $(this);
if ($this.data('before') !== $this.html()) {
$this.data('before', $this.html());
$this.trigger('change');
}
});