trigger an event when contenteditable is changed

前端 未结 12 812
抹茶落季
抹茶落季 2020-11-29 06:14

When a divs value is changed, how Can I trigger an event?

Click this div to edit it
12条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 07:07

    You can simply use focus/blur event with data() function of jQuery :

    // Find all editable content.
    $('[contenteditable=true]')
        // When you click on item, record into data("initialText") content of this item.
        .focus(function() {
            $(this).data("initialText", $(this).html());
        });
        // When you leave an item...
        .blur(function() {
            // ...if content is different...
            if ($(this).data("initialText") !== $(this).html()) {
                // ... do something.
                console.log('New data when content change.');
                console.log($(this).html());
            }
        });
    });
    

    UPDATE: With Vanilla JS

    // Find all editable content.
    var contents = document.querySelectorAll("[contenteditable=true]");
    [].forEach.call(contents, function (content) {
        // When you click on item, record into `data-initial-text` content of this item.
        content.addEventListener("focus", function () {
            content.setAttribute("data-initial-text", content.innerHTML);
        });
        // When you leave an item...
        content.addEventListener("blur", function () {
            // ...if content is different...
            if (content.getAttribute("data-initial-text") !== content.innerHTML) {
                // ... do something.
                console.log("New data when content change.");
                console.log(content.innerHTML);
            }
        });
    });
    

提交回复
热议问题