contenteditable change events

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

    <div oninput="someFunc(event)"></div>
    

    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 });
    
    0 讨论(0)
提交回复
热议问题