contenteditable change events

前端 未结 19 2340
粉色の甜心
粉色の甜心 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:09

    Two options:

    1) For modern (evergreen) browsers: The "input" event would act as an alternative "change" event.

    https://developer.mozilla.org/en-US/docs/Web/Events/input

    document.querySelector('div').addEventListener('input', (e) => {
        // Do something with the "change"-like event
    });
    

    or

    or (with jQuery)

    $('div').on('click', function(e) {
        // Do something with the "change"-like event
    });
    

    2) To account for IE11 and modern (evergreen) browsers: This watches for element changes and their contents inside the div.

    https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

    var div = document.querySelector('div');
    var divMO = new window.MutationObserver(function(e) {
        // Do something on change
    });
    divMO.observe(div, { childList: true, subtree: true, characterData: true });
    

提交回复
热议问题