trigger an event when contenteditable is changed

前端 未结 12 773
抹茶落季
抹茶落季 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 06:44

    Just store the contents to a variable and check if it is different after blur() event. If it is different, store the new contents.

    var contents = $('.changeable').html();
    $('.changeable').blur(function() {
        if (contents!=$(this).html()){
            alert('Handler for .change() called.');
            contents = $(this).html();
        }
    });
    

    example: http://jsfiddle.net/niklasvh/a4QNB/

    0 讨论(0)
  • 2020-11-29 06:44

    I built a jQuery plugin to do this.

    (function ($) {
        $.fn.wysiwygEvt = function () {
            return this.each(function () {
                var $this = $(this);
                var htmlold = $this.html();
                $this.bind('blur keyup paste copy cut mouseup', function () {
                    var htmlnew = $this.html();
                    if (htmlold !== htmlnew) {
                        $this.trigger('change')
                    }
                })
            })
        }
    })(jQuery);
    

    You can simply call $('.wysiwyg').wysiwygEvt();

    You can also remove / add events if you wish

    0 讨论(0)
  • 2020-11-29 06:44

    function myFunction(){
      alert('Handler for .change() called.');
    }
    <div class="changeable" contenteditable="true" onfocusout="myFunction()" > Click this div to edit it <div>

    0 讨论(0)
  • 2020-11-29 06:46

    Here is a jquery-version:

    function fix_contenteditableOnchange(obj)
    {
         div=$(obj);
         var contents = div.html();
         var onchange = div.attr('onchange');
         div.blur(function() {
          if (contents!=$(this).html()){
            eval(onchange);
            fix_contenteditableOnchange(obj);
          }
         });
    }
    

    Try this out.

    0 讨论(0)
  • 2020-11-29 06:52

    It's more simple to do it using EventListener (not a jQuery method):

    document.getElementById("editor").addEventListener("input", function() {
       alert("input event fired");
    }, false);
    

    0 讨论(0)
  • 2020-11-29 06:53

    This is my approach...

    $('.changeable').focusout(function() {
      alert('Handler for .change() called.');
    });
    
    0 讨论(0)
提交回复
热议问题