这个需求涉及在用户输入达到特定长度时,将普通的单行文本输入框(<input type="text">
)动态替换为多行文本输入框(<textarea>
),以提供更好的长文本输入体验。
以下是完整的实现代码示例:
<!DOCTYPE html>
<html>
<head>
<title>文本框替换为Textarea</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.expanded { width: 300px; height: 100px; }
</style>
</head>
<body>
<input type="text" id="myInput" class="text-input" placeholder="输入超过10个字符将变为textarea">
<script>
$(document).ready(function() {
// 定义触发替换的字符长度阈值
const CHAR_LIMIT = 10;
$('#myInput').on('input', function() {
const currentLength = $(this).val().length;
// 当输入长度超过阈值且当前元素是input时,替换为textarea
if (currentLength >= CHAR_LIMIT && $(this).is('input')) {
replaceWithTextarea($(this));
}
});
function replaceWithTextarea($input) {
// 保存原始input的值和属性
const value = $input.val();
const id = $input.attr('id');
const name = $input.attr('name');
const className = $input.attr('class');
// 创建新的textarea元素
const $textarea = $('<textarea>')
.val(value)
.attr('id', id)
.attr('name', name)
.addClass(className)
.addClass('expanded');
// 替换元素
$input.replaceWith($textarea);
// 为新的textarea添加事件监听
$textarea.on('input', function() {
const currentLength = $(this).val().length;
// 如果长度小于阈值且当前是textarea,可以还原为input(可选)
if (currentLength < CHAR_LIMIT && $(this).is('textarea')) {
replaceWithInput($(this));
}
});
}
// 可选:当长度减少时还原为input
function replaceWithInput($textarea) {
const value = $textarea.val();
const id = $textarea.attr('id');
const name = $textarea.attr('name');
const className = $textarea.attr('class').replace('expanded', '').trim();
const $input = $('<input type="text">')
.val(value)
.attr('id', id)
.attr('name', name)
.addClass(className);
$textarea.replaceWith($input);
// 重新绑定事件
$input.on('input', function() {
const currentLength = $(this).val().length;
if (currentLength >= CHAR_LIMIT && $(this).is('input')) {
replaceWithTextarea($(this));
}
});
}
});
</script>
</body>
</html>
这个解决方案提供了基本的实现框架,可以根据具体需求进行调整和扩展。
没有搜到相关的文章