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

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


当前回答

我构建了一个jQuery插件来做到这一点。

(function ($) {
    $.fn.wysiwygEvt = function () {
        return this.each(function () {
            var $this = $(this);
            var htmlold = $this.html();
            $this.bind('blur keyup paste copy cut mouseup', function () {
                var htmlnew = $this.html();
                if (htmlold !== htmlnew) {
                    $this.trigger('change')
                }
            })
        })
    }
})(jQuery);

你可以简单地调用$('.wysiwyg').wysiwygEvt();

如果您愿意,还可以删除/添加事件

其他回答

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

我修改了律法,希望罪恶的答案是这样的,这对我有用。我使用keyup事件而不是keypress,这工作得很好。

$('#editor').on('focus', function() {
  before = $(this).html();
}).on('blur keyup paste', function() { 
  if (before != $(this).html()) { $(this).trigger('change'); }
});

$('#editor').on('change', function() {alert('changed')});

为了避免计时器和“保存”按钮,你可以使用blur事件,当元素失去焦点时触发。但是为了确保元素确实被改变了(不仅仅是聚焦和散焦),它的内容应该与它的上一个版本进行比较。或者使用keydown事件在这个元素上设置一些“脏”标志。

非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'))

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

在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 
 }
}