当用户编辑具有contentteditable属性的div的内容时,我想运行一个函数。onchange事件的等价物是什么?

我使用jQuery,所以使用jQuery的任何解决方案都是首选。谢谢!


当前回答

看看这个想法。 http://pastie.org/1096892

我觉得很接近了。HTML 5确实需要将更改事件添加到规范中。唯一的问题是回调函数在$(this). HTML()中内容实际更新之前计算if (before == $(this). HTML())。setTimeout不起作用,这很可悲。让我知道你的想法。

其他回答

考虑使用MutationObserver。这些观察器设计用于对DOM中的更改做出反应,并作为突变事件的性能替代品。

优点:

当发生任何变化时触发,这很难通过听其他答案所建议的关键事件来实现。例如,所有这些工作都很好:拖放,斜体,复制/剪切/粘贴上下文菜单。 设计时考虑到性能。 简单、直接的代码。比起监听10个事件的代码,理解和调试监听一个事件的代码要容易得多。 谷歌有一个优秀的突变摘要库,使得mutationobserver的使用非常简单。

缺点:

需要最新版本的Firefox (14.0+), Chrome(18+)或IE(11+)。 需要理解的新API 关于最佳实践或案例研究的信息还不多

了解更多:

我写了一个小片段来比较使用mutationobserver处理各种事件。我用了balupton的密码,因为他的答案得到了最多的好评。 Mozilla有一个关于API的优秀页面 看一下MutationSummary库

非JQuery回答…

function makeEditable(elem){
    elem.setAttribute('contenteditable', 'true');
    elem.addEventListener('blur', function (evt) {
        elem.removeAttribute('contenteditable');
        elem.removeEventListener('blur', evt.target);
    });
    elem.focus();
}

要使用它,调用(比如说)一个id="myHeader"的头元素

makeEditable(document.getElementById('myHeader'))

该元素现在可以由用户编辑,直到失去焦点。

根据@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 " > < /脚本>

JQuery的一个简单的答案,我刚刚创建了这段代码,并认为它将对其他人也有帮助

    var cont;

    $("div [contenteditable=true]").focus(function() {
        cont=$(this).html();
    });

    $("div [contenteditable=true]").blur(function() {
        if ($(this).html()!=cont) {
           //Here you can write the code to run when the content change
        }           
    });

const p = document.querySelector('p') const result = document.querySelector('div') const观察者= new MutationObserver((mutationRecords) => { 结果。textContent = mutationRecords[0].target.data / /结果。textContent = p.textContent }) 观察者。观察(p, { characterData:没错, 子树:没错, }) abc contenteditable < p > < / p > < div / >