gpt4 book ai didi

javascript - 在输入类型文本(不是文本区域)中粘贴多行文本

转载 作者:太空狗 更新时间:2023-10-29 16:37:32 25 4
gpt4 key购买 nike

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

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

谢谢!

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

最佳答案

我构建了一个插件来替换 <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

关于javascript - 在输入类型文本(不是文本区域)中粘贴多行文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9535450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com