Catch paste input

后端 未结 17 2091
名媛妹妹
名媛妹妹 2020-11-22 08:09

I\'m looking for a way to sanitize input that I paste into the browser, is this possible to do with jQuery?

I\'ve managed to come up with this so far:



        
17条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 08:44

    This is getting closer to what you might want.

    function sanitize(s) {
      return s.replace(/\bfoo\b/g, "~"); 
    };
    
    $(function() {
     $(":text, textarea").bind("input paste", function(e) {
       try {
         clipboardData.setData("text",
           sanitize(clipboardData.getData("text"))
         );
       } catch (e) {
         $(this).val( sanitize( $(this).val() ) );
       }
     });
    });
    

    Please note that when clipboardData object is not found (on browsers other then IE) you are currently getting the element's full value + the clipboard'ed value.

    You can probably do some extra steps to dif the two values, before an input & after the input, if you really are only after what data was truly pasted into the element.

提交回复
热议问题