【问题标题】:Paste multiline text in input type text (not textarea)在输入类型文本中粘贴多行文本(不是 textarea)
【发布时间】:2012-03-21 02:00:03
【问题描述】:

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

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

谢谢!

更新 here 有一个 JSFiddle 的示例...愚蠢的 IE,在 FF 中效果很好。

【问题讨论】:

  • 请给我jsFiddle好吗?
  • 可以提供样品吗?我在 JSfiddle 中对此进行了测试,没有任何问题。
  • 我刚刚做了例子......这是愚蠢的IE

标签: javascript jquery html multiline textinput


【解决方案1】:

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

// 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 = $("<textarea></textarea>");

  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");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input type="text" style="width: 700px;" class="txt" />
<button>Change value of txt</button>

View on JSFiddle

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 当 paste 事件被触发时,除了第一行之外,我已经丢失了所有行。
    • 哦,伙计。那会很麻烦...我认为解决方案是使用textarea 接受粘贴,然后将值复制到您的input
    【解决方案3】:

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

    Is it possible to get pasted text without using the setTimeout() function?

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

    【讨论】:

    • 在 Firefox 中,这种方式非常完美(正如我的方法)。遗憾的是,在 IE 中它没有,它还会截断第一行之后的文本。
    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多