捕获粘贴输入

发布于 2024-07-15 12:42:29 字数 282 浏览 8 评论 0原文

我正在寻找一种方法来清理粘贴到浏览器中的输入,这可以用 jQuery 实现吗?

到目前为止,我已经设法想出这一点:

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

不幸的是,由于这个“小”问题,我的开发陷入了困境。 如果有人能给我指明正确的方向,我真的会让我成为一个快乐的露营者。

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:

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

Unfortunately my development has come to a screeching hold because of this "minor" issue.
I would really make me a happy camper if someone could point me to the right direction.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

小猫一只 2024-07-22 12:42:29

好吧,刚刚遇到了同样的问题..我走了很长一段路,

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

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

E.

OK, just bumped into the same issue.. I went around the long way

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

Just a small timeout till .val() func can get populated.

E.

故事还在继续 2024-07-22 12:42:29

实际上,您可以直接从事件获取该值。 但如何到达它有点迟钝。

如果您不希望它通过,则返回 false。

$(this).on('paste', function(e) {

  var pasteData = e.originalEvent.clipboardData.getData('text')

});

You can actually grab the value straight from the event. Its a bit obtuse how to get to it though.

Return false if you don't want it to go through.

$(this).on('paste', function(e) {

  var pasteData = e.originalEvent.clipboardData.getData('text')

});
冷血 2024-07-22 12:42:29

为了跨平台兼容性,它应该处理 oninput 和 onpropertychange 事件:

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

For cross platform compatibility, it should handle oninput and onpropertychange events:

$ (something).bind ("input propertychange", function (e) {
    // check for paste as in example above and
    // do something
})
尝蛊 2024-07-22 12:42:29

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

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

现在我只需要存储插入符号位置并附加到该位置,然后我就准备好了......我想:)

I sort of fixed it by using the following code:

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

Now I just need to store the caret location and append to that position then I'm all set... I think :)

烦人精 2024-07-22 12:42:29

嗯...我认为您可以使用e.clipboardData来捕获正在粘贴的数据。 如果没有成功,请查看此处

$(this).live("paste", function(e) {
    alert(e.clipboardData); // [object Clipboard]
});

Hmm... I think you can use e.clipboardData to catch the data being pasted. If it doesn't pan out, have a look here.

$(this).live("paste", function(e) {
    alert(e.clipboardData); // [object Clipboard]
});
聽兲甴掵 2024-07-22 12:42:29

侦听粘贴事件并设置 keyup 事件侦听器。 在 keyup 上,捕获值并删除 keyup 事件侦听器。

$('.inputTextArea').bind('paste', function (e){
    $(e.target).keyup(getInput);
});
function getInput(e){
    var inputText = $(e.target).val();
    $(e.target).unbind('keyup');
}

Listen for the paste event and set a keyup event listener. On keyup, capture the value and remove the keyup event listener.

$('.inputTextArea').bind('paste', function (e){
    $(e.target).keyup(getInput);
});
function getInput(e){
    var inputText = $(e.target).val();
    $(e.target).unbind('keyup');
}
凡间太子 2024-07-22 12:42:29
$("#textboxid").on('input propertychange', function () {
    //perform operation
        });

它会工作得很好。

$("#textboxid").on('input propertychange', function () {
    //perform operation
        });

It will work fine.

身边 2024-07-22 12:42:29

这越来越接近您可能想要的。

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

请注意,当找不到 ClipboardData 对象时(在 IE 以外的浏览器上),您当前获取的是元素的完整值 + 剪贴板的值。

在输入和输入之前,您可能可以执行一些额外的步骤来区分这两个值。 输入之后,如果您确实只是在数据真正粘贴到元素之后。

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.

美人骨 2024-07-22 12:42:29
 $('').bind('input propertychange', function() {....});                      

这适用于鼠标粘贴事件。

 $('').bind('input propertychange', function() {....});                      

This will work for mouse paste event.

国际总奸 2024-07-22 12:42:29

比较字段的原始值和字段的更改值并扣除差值作为粘贴的值如何? 即使字段中存在现有文本,这也可以正确捕获粘贴的文本。

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

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);
    });
});
聚集的泪 2024-07-22 12:42:29

此代码对我有用,可以通过右键单击粘贴或直接复制粘贴,

   $('.textbox').on('paste input propertychange', function (e) {
        $(this).val( $(this).val().replace(/[^0-9.]/g, '') );
    })

当我粘贴第 1 节:人工成本时,它在文本框中变为1

为了仅允许浮点值,我使用此代码

 //only decimal
    $('.textbox').keypress(function(e) {
        if(e.which == 46 && $(this).val().indexOf('.') != -1) {
            e.preventDefault();
        } 
       if (e.which == 8 || e.which == 46) {
            return true;
       } else if ( e.which < 48 || e.which > 57) {
            e.preventDefault();
      }
    });

This code is working for me either paste from right click or direct copy paste

   $('.textbox').on('paste input propertychange', function (e) {
        $(this).val( $(this).val().replace(/[^0-9.]/g, '') );
    })

When i paste Section 1: Labour Cost it becomes 1 in text box.

To allow only float value i use this code

 //only decimal
    $('.textbox').keypress(function(e) {
        if(e.which == 46 && $(this).val().indexOf('.') != -1) {
            e.preventDefault();
        } 
       if (e.which == 8 || e.which == 46) {
            return true;
       } else if ( e.which < 48 || e.which > 57) {
            e.preventDefault();
      }
    });
未蓝澄海的烟 2024-07-22 12:42:29

请参阅此示例: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
})

See this example: http://www.p2e.dk/diverse/detectPaste.htm

It essentialy tracks every change with oninput event and then checks if it’s a paste by string comparison. Oh, and in IE there’s an onpaste event. So:

$ (something).bind ("input paste", function (e) {
    // check for paste as in example above and
    // do something
})
白芷 2024-07-22 12:42:29
document.addEventListener('paste', function(e){
    if(e.clipboardData.types.indexOf('text/html') > -1){
        processDataFromClipboard(e.clipboardData.getData('text/html'));
        e.preventDefault();

        ...
    }
});

此外:

document.addEventListener('paste', function(e){
    if(e.clipboardData.types.indexOf('text/html') > -1){
        processDataFromClipboard(e.clipboardData.getData('text/html'));
        e.preventDefault();

        ...
    }
});

Further:

庆幸我还是我 2024-07-22 12:42:29

此方法使用 jqueriescontents().unwrap()。

  1. 首先,检测粘贴事件向
  2. 我们要粘贴的元素中已有的标签添加一个唯一的类。
  3. 在给定的超时后,扫描所有不包含您之前设置的类的内容展开标签。 注意:此方法不会删除像
    这样的自闭合标签
    请参阅下面的示例。

    //查找所有子级 .find('*') 并将类 .within .addClass("within") 添加到所有标签 
      $('#answer_text').find('*').each(function () { 
      $(this).addClass("内"); 
      }); 
      设置超时(函数(){ 
      $('#answer_text').find('*').each(function () { 
          //如果当前子级没有指定的类,则解开其内容 
          $(this).not(".within").contents().unwrap(); 
      }); 
      }, 0); 
      

This method uses jqueries contents().unwrap().

  1. First, detect the paste event
  2. Add a unique class to the tags that are already in the element into which we are pasting.
  3. After a given timeout scan through all the contents unwrapping tags that don't have the class that you set earlier. Note: This method does not remove self closing tags like
    See an example below.

    //find all children .find('*') and add the class .within .addClass("within") to all tags
    $('#answer_text').find('*').each(function () {
    $(this).addClass("within");
    });
    setTimeout(function() {
    $('#answer_text').find('*').each(function () {
        //if the current child does not have the specified class unwrap its contents
        $(this).not(".within").contents().unwrap();
    });
    }, 0);
    
时光磨忆 2024-07-22 12:42:29

用于从具有类 portlet-form-input-field 的所有字段中删除特殊字符的脚本:

// Remove special chars from input field on paste
jQuery('.portlet-form-input-field').bind('paste', function(e) {
    var textInput = jQuery(this);
    setTimeout(function() {
        textInput.val(replaceSingleEndOfLineCharactersInString(textInput.val()));
    }, 200);
});

function replaceSingleEndOfLineCharactersInString(value) {
    <%
        // deal with end-of-line characters (\n or \r\n) that will affect string length calculation,
        // also remove all non-printable control characters that can cause XML validation errors
    %>
    if (value != "") {
        value = value.replace(/(\x00|\x01|\x02|\x03|\x04|\x05|\x06|\x07|\x08|\x0B|\x0C|\x0E|\x0F|\x10|\x11|\x12|\x13|\x14|\x15|\x16|\x17|\x18|\x19|\x1A|\x1B|\x1C|\x1D|\x1E|\x1F|\x7F)/gm,'');
        return value = value.replace(/(\r\n|\n|\r)/gm,'##').replace(/(\#\#)/gm,"\r\n");
    }
}

Script to remove special characters from all fields with class portlet-form-input-field:

// Remove special chars from input field on paste
jQuery('.portlet-form-input-field').bind('paste', function(e) {
    var textInput = jQuery(this);
    setTimeout(function() {
        textInput.val(replaceSingleEndOfLineCharactersInString(textInput.val()));
    }, 200);
});

function replaceSingleEndOfLineCharactersInString(value) {
    <%
        // deal with end-of-line characters (\n or \r\n) that will affect string length calculation,
        // also remove all non-printable control characters that can cause XML validation errors
    %>
    if (value != "") {
        value = value.replace(/(\x00|\x01|\x02|\x03|\x04|\x05|\x06|\x07|\x08|\x0B|\x0C|\x0E|\x0F|\x10|\x11|\x12|\x13|\x14|\x15|\x16|\x17|\x18|\x19|\x1A|\x1B|\x1C|\x1D|\x1E|\x1F|\x7F)/gm,'');
        return value = value.replace(/(\r\n|\n|\r)/gm,'##').replace(/(\#\#)/gm,"\r\n");
    }
}
明月松间行 2024-07-22 12:42:29

事实证明这是非常虚幻的。 在执行粘贴事件函数内的代码之前,不会更新输入的值。 我尝试从粘贴事件函数内调用其他事件,但输入值仍未使用任何事件函数内的粘贴文本进行更新。 这是除 keyup 之外的所有事件。 如果您从粘贴事件函数中调用 keyup,则可以从 keyup 事件函数中清理粘贴的文本。 就像这样...

$(':input').live
(
    'input paste',
    function(e)
    {
        $(this).keyup();
    }
);

$(':input').live
(
    'keyup',
    function(e)
    {
        // sanitize pasted text here
    }
);

这里有一个警告。 在 Firefox 中,如果您在每次按键时重置输入文本,并且文本长于输入宽度允许的可视区域,则在每次按键时重置值会破坏浏览器自动将文本滚动到插入符号位置的功能。正文结束。 相反,文本会滚动回开头,使插入符号不可见。

This proved to be quite illusive. The value of the input is not updated prior to the execution of the code inside the paste event function. I tried calling other events from within the paste event function but the input value is still not updated with the pasted text inside the function of any events. That is all events apart from keyup. If you call keyup from within the paste event function you can sanitize the pasted text from within the keyup event function. like so...

$(':input').live
(
    'input paste',
    function(e)
    {
        $(this).keyup();
    }
);

$(':input').live
(
    'keyup',
    function(e)
    {
        // sanitize pasted text here
    }
);

There is one caveat here. In Firefox, if you reset the input text on every keyup, if the text is longer than the viewable area allowed by the input width, then resetting the value on every keyup breaks the browser functionality that auto scrolls the text to the caret position at the end of the text. Instead the text scrolls back to the beginning leaving the caret out of view.

℡Ms空城旧梦 2024-07-22 12:42:29

这里有一个警告。 在 Firefox 中,如果您在每次按键时重置输入文本,并且文本长于输入宽度允许的可视区域,则在每次按键时重置值会破坏浏览器自动将文本滚动到插入符号位置的功能。正文结束。 相反,文本会滚动回开头,使插入符号不可见。

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

There is one caveat here. In Firefox, if you reset the input text on every keyup, if the text is longer than the viewable area allowed by the input width, then resetting the value on every keyup breaks the browser functionality that auto scrolls the text to the caret position at the end of the text. Instead the text scrolls back to the beginning leaving the caret out of view.

function scroll(elementToBeScrolled) 
{
     //this will reset the scroll to the bottom of the viewable area. 
     elementToBeScrolled.topscroll = elementToBeScrolled.scrollheight;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文