Catch paste input

后端 未结 17 2100
名媛妹妹
名媛妹妹 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:23

    How about comparing the original value of the field and the changed value of the field and deducting the difference as the pasted value? This catches the pasted text correctly even if there is existing text in the field.

    http://jsfiddle.net/6b7sK/

    function text_diff(first, second) {
        var start = 0;
        while (start < first.length && first[start] == second[start]) {
            ++start;
        }
        var end = 0;
        while (first.length - end > start && first[first.length - end - 1] == second[second.length - end - 1]) {
            ++end;
        }
        end = second.length - end;
        return second.substr(start, end - start);
    }
    $('textarea').bind('paste', function () {
        var self = $(this);
        var orig = self.val();
        setTimeout(function () {
            var pasted = text_diff(orig, $(self).val());
            console.log(pasted);
        });
    });
    

提交回复
热议问题