源码:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>/* 样式调整 */.input-container {display: flex;align-items: center; /* 垂直居中对齐 */}#input {/* flex: 1; *//* 输入框占据剩余空间 */margin-right: 10px; /* 右侧留出一定的间隔 */}#counter {font-size: 12px; /* 字号调整 */}.max-length-reached {color: red; /* 计数器文字变成红色 */}</style>
</head>
<body><div class="input-container"><input id="input" type="text" maxlength="30"><div id="counter">0/30</div></div><script>// 获取输入框和计数器的元素const input = document.getElementById('input');const counter = document.getElementById('counter');const maxLength = parseInt(input.getAttribute('maxlength')); // 获取最大输入长度并转换为整数// 监听输入框的输入事件input.addEventListener('input', function() {// 获取已输入的字数const enteredLength = input.value.length;// 更新计数器的文本内容counter.textContent = `${enteredLength}/${maxLength}`;// 如果已输入的字数达到最大限制,将计数器的颜色设为红色if (enteredLength === maxLength) {counter.classList.add('max-length-reached');} else {counter.classList.remove('max-length-reached');}});</script>
</body>
</html>
运行结果: