JS实现inpubox
实现 InputBox 的基本结构
使用 HTML 和 CSS 创建一个基础的输入框结构,确保样式简洁且易于扩展。
<div class="input-box">
<input type="text" placeholder="Enter something..." class="input-field" />
<button class="input-button">Submit</button>
</div>
.input-box {
display: flex;
border: 1px solid #ccc;
border-radius: 4px;
overflow: hidden;
width: 300px;
}
.input-field {
flex: 1;
padding: 10px;
border: none;
outline: none;
}
.input-button {
padding: 10px;
background-color: #007bff;
color: white;
border: none;
cursor: pointer;
}
.input-button:hover {
background-color: #0056b3;
}
添加事件监听与交互逻辑
通过 JavaScript 为输入框和按钮添加交互功能,例如提交输入内容或实时验证。

const inputField = document.querySelector('.input-field');
const inputButton = document.querySelector('.input-button');
inputButton.addEventListener('click', () => {
const value = inputField.value.trim();
if (value) {
alert(`Submitted: ${value}`);
inputField.value = '';
} else {
alert('Input cannot be empty!');
}
});
inputField.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
inputButton.click();
}
});
扩展功能:实时输入验证
为输入框添加实时验证逻辑,例如限制输入长度或检查特定格式。

inputField.addEventListener('input', () => {
const value = inputField.value;
if (value.length > 20) {
inputField.style.borderColor = 'red';
} else {
inputField.style.borderColor = '#ccc';
}
});
动态生成 InputBox
通过 JavaScript 动态生成输入框组件,适用于需要动态添加输入框的场景。
function createInputBox(placeholder, buttonText) {
const container = document.createElement('div');
container.className = 'input-box';
const input = document.createElement('input');
input.type = 'text';
input.placeholder = placeholder;
input.className = 'input-field';
const button = document.createElement('button');
button.className = 'input-button';
button.textContent = buttonText;
button.addEventListener('click', () => {
alert(`Submitted: ${input.value}`);
});
container.appendChild(input);
container.appendChild(button);
return container;
}
document.body.appendChild(createInputBox('Enter name...', 'Save'));
封装为可复用组件
将输入框逻辑封装为类或模块,便于在项目中复用。
class InputBox {
constructor(options) {
this.container = document.createElement('div');
this.container.className = 'input-box';
this.input = document.createElement('input');
this.input.type = 'text';
this.input.placeholder = options.placeholder || 'Enter...';
this.input.className = 'input-field';
this.button = document.createElement('button');
this.button.className = 'input-button';
this.button.textContent = options.buttonText || 'Submit';
this.button.addEventListener('click', () => {
if (options.onSubmit) {
options.onSubmit(this.input.value);
}
});
this.container.appendChild(this.input);
this.container.appendChild(this.button);
}
appendTo(element) {
element.appendChild(this.container);
}
}
const myInputBox = new InputBox({
placeholder: 'Type here...',
buttonText: 'Send',
onSubmit: (value) => alert(value)
});
myInputBox.appendTo(document.body);






