在输入类型文本中粘贴多行文本(不是textarea)

我有一个input type text ,用户输入数字代码分隔,或由- (作一个范围)。 我想允许我网站的用户粘贴代码列表。 我已经设法绑定粘贴事件(使用jQuery)并解析输入字符串删除空格和所有内容。

当用户代码列表是多行时,问题开始。 在浏览器尝试将其插入输入之前,我没有找到任何方法来操作该文本,因此字符串在第一行的末尾被截断。 在浏览器截断它之前有没有办法操纵字符串?

谢谢!

更新 这里有一个JSFiddle的例子…愚蠢的IE,在FF这很好用。

通过删除换行符将字符串转换为一行。

 "multiline\ntext\nline3".split('\n').join(''); 

检查这个SO线程。 它链接到一个jsfiddle,它具有我认为可以处理您的问题的代码

是否可以在不使用setTimeout()函数的情况下获取粘贴文本?

链接到jsfiddle http://jsfiddle.net/pxfunc/KDLjf/

您可以在IE下使用以下解决方法。 请阅读代码示例中的注释 –

  jQuery("input").bind("paste", function() { var element = jQuery(this); setTimeout(function () { var text = element.val(); // window.clipboardData works only in IE. // For other browsers, element.val() should work if(window.clipboardData){ text = window.clipboardData.getData('Text'); } matches = text.match(/[^0-9]+/g); if (matches != null) { for (var i = 0; i < matches.length; i++) { text = text.replace(matches[i], ((matches[i].indexOf("-") < 0) ? "," : "-")); } element.val(text); } }, 100); }); 

我构建了一个插件来替换的输入。 这里是:

 // Debe llamarse al plugin antes de construir cualquier referencia al elemento. // El nuevo elemento debe seleccionarse por id, por name o por clases. // En el momento de llamar al plugin el elemento debe estar visible. // Translate: // The plugin must be called before saving any reference to the element. // The new element must be selected by its id, name or classes, not by the tag "input". // When the plugin is called the element must be visible. $.fn.acceptMultiline = function() { var txt = $(this), txtArea = $(""); if (txt.attr("style") != undefined) txtArea.attr("style", txt.attr("style")); if (txt.attr("class") != undefined) txtArea.attr("class", txt.attr("class")); if (txt.attr("name") != undefined) txtArea.attr("name", txt.attr("name")); if (txt.attr("id") != undefined) txtArea.attr("id", txt.attr("id")); txtArea .width(txt.width()) .height(txt.height()) .css("resize", "none"); txt.after(txtArea) .remove(); txtArea.on("input", function() { txtArea.val(txtArea.val().replace(/\r\n/g, " ").replace(/\r/g, " ").replace(/\n/g, " ")); }); }; $(":text").acceptMultiline(); $("button").on("click", function() { $(".txt").val($(".txt").val() + "pepe"); });