在 HTML 中,可以使用 <input>
标签来创建输入框。要创建带有计数器的输入框,可以借助 JavaScript 来实现。具体步骤如下:
<input>
标签,并指定其 id 属性,以便在 JavaScript 中获取该元素。<input type="text" id="inputBox">
<input>
元素,并为其添加一个事件监听器,用于监听其输入变化事件。const inputBox = document.getElementById("inputBox");
inputBox.addEventListener("input", function() {
// 在这里编写实现计数器的代码
});
value.length
属性获取输入框中的字符数,并将其显示在页面上。const inputBox = document.getElementById("inputBox");
const counter = document.createElement("span"); // 创建一个 <span> 元素用于显示计数器
counter.innerText = `0/${inputBox.maxLength}`; // 设置计数器的初始值
inputBox.insertAdjacentElement("afterend", counter); // 将计数器插入到 <input> 元素之后
inputBox.addEventListener("input", function() {
const length = inputBox.value.length;
counter.innerText = `${length}/${inputBox.maxLength}`; // 更新计数器的值
});
在上述代码中,我们在 <input>
元素之后插入了一个 <span>
元素,用于显示计数器的值。然后,我们为 <input>
元素添加了一个事件监听器,监听其输入变化事件。每当用户输入字符时,计数器的值就会更新。注意,我们使用了 insertAdjacentElement
方法将计数器插入到 <input>
元素之后。该方法可以在指定元素之前或之后插入一个新元素,可以传入的第一个参数为 beforebegin
、afterbegin
、beforeend
或 afterend
,分别表示插入到指定元素的前面、内部的开头、内部的结尾或后面。
最终效果如下: