contenteditable change events

前端 未结 19 2539
粉色の甜心
粉色の甜心 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 02:03

    Consider using MutationObserver. These observers are designed to react to changes in the DOM, and as a performant replacement to Mutation Events.

    Pros:

    • Fires when any change occurs, which is difficult to achieve by listening to key events as suggested by other answers. For example, all of these work well: drag & drop, italicizing, copy/cut/paste through context menu.
    • Designed with performance in mind.
    • Simple, straightforward code. It's a lot easier to understand and debug code that listens to one event rather than code that listens to 10 events.
    • Google has an excellent mutation summary library which makes using MutationObservers very easy.

    Cons:

    • Requires a very recent version of Firefox (14.0+), Chrome (18+), or IE (11+).
    • New API to understand
    • Not a lot of information available yet on best practices or case studies

    Learn more:

    • I wrote a little snippet to compare using MutationObserers to handling a variety of events. I used balupton's code since his answer has the most upvotes.
    • Mozilla has an excellent page on the API
    • Take a look at the MutationSummary library

提交回复
热议问题