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

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


当前回答

onchange事件不会在具有contentEditable属性的元素被更改时触发,建议的方法是添加一个按钮,以“保存”版本。

检查这个插件,它以这种方式处理问题:

创建一个快速的jQuery contentteditable插件

其他回答

onchange事件不会在具有contentEditable属性的元素被更改时触发,建议的方法是添加一个按钮,以“保存”版本。

检查这个插件,它以这种方式处理问题:

创建一个快速的jQuery contentteditable插件

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

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

这个帖子在我调查这个主题的时候非常有帮助。

我把这里的一些代码修改成一个jQuery插件,这样它就可以以一种可重用的形式使用,主要是为了满足我的需求,但其他人可能更喜欢一个简单的界面来使用可满足的标记。

https://gist.github.com/3410122

更新:

由于其日益流行的插件已被Makesites.org采用

发展将从这里开始:

https://github.com/makesites/jquery-contenteditable

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