当用户编辑具有contentteditable属性的div的内容时,我想运行一个函数。onchange事件的等价物是什么?
我使用jQuery,所以使用jQuery的任何解决方案都是首选。谢谢!
当用户编辑具有contentteditable属性的div的内容时,我想运行一个函数。onchange事件的等价物是什么?
我使用jQuery,所以使用jQuery的任何解决方案都是首选。谢谢!
当前回答
在Angular 2+中
<div contentEditable (input)="type($event)">
Value
</div>
@Component({
...
})
export class ContentEditableComponent {
...
type(event) {
console.log(event.data) // <-- The pressed key
console.log(event.path[0].innerHTML) // <-- The content of the div
}
}
其他回答
您需要使用输入事件类型
Demo
HTML
<div id="editor" contenteditable="true" >Some text here</div>
JS
const input = document.getElementById('editor');
input.addEventListener('input', updateValue);
function updateValue(e) {
console.log(e.target);
}
知道更多
考虑使用MutationObserver。这些观察器设计用于对DOM中的更改做出反应,并作为突变事件的性能替代品。
优点:
当发生任何变化时触发,这很难通过听其他答案所建议的关键事件来实现。例如,所有这些工作都很好:拖放,斜体,复制/剪切/粘贴上下文菜单。 设计时考虑到性能。 简单、直接的代码。比起监听10个事件的代码,理解和调试监听一个事件的代码要容易得多。 谷歌有一个优秀的突变摘要库,使得mutationobserver的使用非常简单。
缺点:
需要最新版本的Firefox (14.0+), Chrome(18+)或IE(11+)。 需要理解的新API 关于最佳实践或案例研究的信息还不多
了解更多:
我写了一个小片段来比较使用mutationobserver处理各种事件。我用了balupton的密码,因为他的答案得到了最多的好评。 Mozilla有一个关于API的优秀页面 看一下MutationSummary库
根据@balupton的回答:
美元(文档)。On ('focus', '[contenteditable]', e => { Const self = $(e.target) 自我。数据(‘前’,self.html ()) }) 美元(文档)。On ('blur', '[contenteditable]', e => { Const self = $(e.target) If (self.data('before') !== self.html()) { self.trigger(“变化”) } }) < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本>
在MutationEvents下使用domcharacterdatmodified会导致同样的结果。超时设置是为了防止发送错误的值(例如,在Chrome中,我有一些空格键的问题)
var timeoutID;
$('[contenteditable]').bind('DOMCharacterDataModified', function() {
clearTimeout(timeoutID);
$that = $(this);
timeoutID = setTimeout(function() {
$that.trigger('change')
}, 50)
});
$('[contentEditable]').bind('change', function() {
console.log($(this).text());
})
JSFIDDLE例子
在Angular 2+中
<div contentEditable (input)="type($event)">
Value
</div>
@Component({
...
})
export class ContentEditableComponent {
...
type(event) {
console.log(event.data) // <-- The pressed key
console.log(event.path[0].innerHTML) // <-- The content of the div
}
}