contenteditable change events

前端 未结 19 2311
粉色の甜心
粉色の甜心 2020-11-22 01:36

I want to run a function when a user edits the content of a div with contenteditable attribute. What\'s the equivalent of an onchange

19条回答
  •  爱一瞬间的悲伤
    2020-11-22 01:49

    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.

    UPDATE 29 October 2014

    The HTML5 input event is the answer in the long term. At the time of writing, it is supported for contenteditable elements in current Mozilla (from Firefox 14) and WebKit/Blink browsers, but not IE.

    Demo:

    document.getElementById("editor").addEventListener("input", function() {
        console.log("input event fired");
    }, false);
    Please type something in here

    Demo: http://jsfiddle.net/ch6yn/2691/

提交回复
热议问题