jQuery event for html change in a div element?

前端 未结 5 2129
抹茶落季
抹茶落季 2021-02-14 16:48

Long story short - I have an editable

and I want to clear formatting when someone pastes something in. Since jQuery has no control over the clipboard an
相关标签:
5条回答
  • 2021-02-14 17:23

    I think TinyMCE for JQuery can do the work for you.

    0 讨论(0)
  • 2021-02-14 17:25

    This may be a solution for you possibly: http://garage.pimentech.net/scripts_doc_jquery_jframe/

    0 讨论(0)
  • 2021-02-14 17:26

    You can make use of .keyup() for copy and pasting. The right click followed by choosing paste in the context menu doesn't seem to record a click, so .click() doesn't work.... instead use setInterval() to check every X seconds to capture right click pastes.

    Not sure if you can bind .keyup() to the div (whether the div is focusable across all browsers), but all keyups bubble up to the document, so $(document) will always work.

    $(function() {
    
          // Get initial text:
        var previous = $("#mydiv").text();
    
          // Make DIV editable if clicked
        $("#mydiv").click(function() { this.contentEditable = 'true'; });
    
          // Create a function for what to do if there is a change:
        $check = function() {
    
              // Check for a change
            if ($("#mydiv").text() != previous) {
                // What to do if there's been a change
                // ...
            }
    
              // Store what contents are for later comparison
            previous = $("#mydiv").text();        
        }
    
          // Add the div changed handler to both keyup (ctr + v)
          //   and mouseclick (right click paste)
        $(document).keyup($check);
          // Right click work around is to check every Xs
        setInterval(function() { $check(); }, 1000);
    });​
    

    jsFiddle Example


    This works with pasting.... it captures ctr, shift, etc keys. (if you try it out w ctr-v and you release one key after the other, then keep an eye on the status, since the status will only show changed after the release of the first key and same after the release of the second.... as it should).


    Note: I do like having both a .keyup() handler and a setInterval, since this guarantees that the feedback is instant for keystrokes.... even though there might be a lag after a right click paste.

    0 讨论(0)
  • 2021-02-14 17:26

    You can use a 'keydown' event - it will capture shift key presses so works for pasting, as well as the delete key.

    If you need to detect whether the content has changed, store the old content and compare when the event is fired.

    To capture paste by mouse, you'll probably need to compare current content to old content periodically based on a timer. You could reduce some overhead by activating the timer on focus, and stopping it on blur.

    0 讨论(0)
  • 2021-02-14 17:44

    Use a <textarea> instead

    0 讨论(0)
提交回复
热议问题