我正在寻找一种方法来消毒输入,我粘贴到浏览器,这是可能的用jQuery做吗?

到目前为止,我已经想出了这个:

$(this).live(pasteEventName, function(e) {
 // this is where i would like to sanitize my input
 return false;
}

不幸的是,我的发展因为这个“小”问题而戛然而止。 如果有人能给我指出正确的方向,我真的会让我成为一个快乐的露营者。


当前回答

这里有一个警告。在Firefox中,如果您重置每个键上的输入文本,如果文本长于输入宽度允许的可视区域,则重置每个键上的值将破坏浏览器自动将文本滚动到文本末尾的插入号位置的功能。相反,文本将滚动回开始,而插入符号则不在视图中。

function scroll(elementToBeScrolled) 
{
     //this will reset the scroll to the bottom of the viewable area. 
     elementToBeScrolled.topscroll = elementToBeScrolled.scrollheight;
}

其他回答

好吧,正好碰到了同样的问题。我绕了很长的路

$('input').on('paste', function () {
  var element = this;
  setTimeout(function () {
    var text = $(element).val();
    // do something with text
  }, 100);
});

只是一个小的超时,直到.val() func可以填充。

E.

我通过使用以下代码修复了它:

$("#editor").live('input paste',function(e){
    if(e.target.id == 'editor') {
        $('<textarea></textarea>').attr('id', 'paste').appendTo('#editMode');
        $("#paste").focus();
        setTimeout($(this).paste, 250);
    }
});

现在我只需要存储插入符号的位置并附加到该位置,然后我就全部设置好了……我认为:)

将字段的原始值与更改后的值进行比较,然后扣除差值作为粘贴值,如何?这将正确地捕获粘贴的文本,即使字段中存在文本。

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);
    });
});

请看这个例子:http://www.p2e.dk/diverse/detectPaste.htm

它本质上用oninput事件跟踪每个更改,然后通过字符串比较检查它是否是粘贴。哦,在IE中有一个onpaste事件。所以:

$ (something).bind ("input paste", function (e) {
    // check for paste as in example above and
    // do something
})

这里有一个警告。在Firefox中,如果您重置每个键上的输入文本,如果文本长于输入宽度允许的可视区域,则重置每个键上的值将破坏浏览器自动将文本滚动到文本末尾的插入号位置的功能。相反,文本将滚动回开始,而插入符号则不在视图中。

function scroll(elementToBeScrolled) 
{
     //this will reset the scroll to the bottom of the viewable area. 
     elementToBeScrolled.topscroll = elementToBeScrolled.scrollheight;
}