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

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


当前回答

2022年更新

正如评论中所指出的,这并没有回答所提出的问题,即需要更改事件而不是输入事件的等价物。不过,我还是把它留在这里吧。

原来的答案

I'd suggest attaching listeners to key events fired by the editable element, though you need to be aware that keydown and keypress events are fired before the content itself is changed. This won't cover every possible means of changing the content: the user can also use cut, copy and paste from the Edit or context browser menus, so you may want to handle the cut copy and paste events too. Also, the user can drop text or other content, so there are more events there (mouseup, for example). You may want to poll the element's contents as a fallback.

2014年10月29日更新

从长远来看,HTML5输入事件是答案。在撰写本文时,当前的Mozilla(来自Firefox 14)和WebKit/Blink浏览器支持可满足的元素,但不支持IE。

演示:

. getelementbyid(“编辑器”)。addEventListener("input", function() { Console.log("触发的输入事件"); },假); <div contentteditable ="true" id="editor">请在这里输入一些内容</div>

演示:http://jsfiddle.net/ch6yn/2691/

其他回答

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

优点:

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

缺点:

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

了解更多:

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

以下是对我有效的方法:

   var clicked = {} 
   $("[contenteditable='true']").each(function(){       
        var id = $(this).attr("id");
        $(this).bind('focus', function() {
            // store the original value of element first time it gets focus
            if(!(id in clicked)){
                clicked[id] = $(this).html()
            }
        });
   });

   // then once the user clicks on save
   $("#save").click(function(){
            for(var id in clicked){
                var original = clicked[id];
                var current = $("#"+id).html();
                // check if value changed
                if(original != current) save(id,current);
            }
   });

我构建了一个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();

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

这里有一个更有效的版本,它对所有可内容使用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');
    }
});

项目在这里:https://github.com/balupton/html5edit

2022年更新

正如评论中所指出的,这并没有回答所提出的问题,即需要更改事件而不是输入事件的等价物。不过,我还是把它留在这里吧。

原来的答案

I'd suggest attaching listeners to key events fired by the editable element, though you need to be aware that keydown and keypress events are fired before the content itself is changed. This won't cover every possible means of changing the content: the user can also use cut, copy and paste from the Edit or context browser menus, so you may want to handle the cut copy and paste events too. Also, the user can drop text or other content, so there are more events there (mouseup, for example). You may want to poll the element's contents as a fallback.

2014年10月29日更新

从长远来看,HTML5输入事件是答案。在撰写本文时,当前的Mozilla(来自Firefox 14)和WebKit/Blink浏览器支持可满足的元素,但不支持IE。

演示:

. getelementbyid(“编辑器”)。addEventListener("input", function() { Console.log("触发的输入事件"); },假); <div contentteditable ="true" id="editor">请在这里输入一些内容</div>

演示:http://jsfiddle.net/ch6yn/2691/