jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。字数文本框通常是指限制用户输入字符数量的文本输入框。
以下是一个使用 jQuery 实现固定字数限制的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery 字数文本框</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<input type="text" id="textInput" placeholder="请输入内容">
<span id="charCount">0</span> / 100
<script>
$(document).ready(function() {
var maxLength = 100;
$('#textInput').on('input', function() {
var currentLength = $(this).val().length;
$('#charCount').text(currentLength);
if (currentLength > maxLength) {
$(this).val($(this).val().substring(0, maxLength));
$('#charCount').text(maxLength);
}
});
});
</script>
</body>
</html>
input
事件而不是 keyup
或 keydown
事件,因为 input
事件在输入框内容变化时立即触发。$('#textInput').on('input', function() {
var currentLength = $(this).val().length;
$('#charCount').text(currentLength);
if (currentLength > maxLength) {
var value = $(this).val().substring(0, maxLength);
$(this).val(value);
$('#charCount').text(maxLength);
// 重新设置光标位置
var cursorPosition = value.length;
$(this)[0].setSelectionRange(cursorPosition, cursorPosition);
}
});
通过以上方法,可以有效地实现字数文本框的功能,并解决常见的相关问题。
领取专属 10元无门槛券
手把手带您无忧上云