JS实现inpubox
实现 InputBox 的基本结构
使用 HTML 创建一个简单的输入框结构,包含一个输入框和一个按钮。
<div class="input-box">
<input type="text" id="inputField" placeholder="Enter text here">
<button id="submitBtn">Submit</button>
</div>
添加样式
通过 CSS 美化输入框和按钮,使其更具交互性。
.input-box {
display: flex;
gap: 10px;
margin: 20px;
}
#inputField {
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
width: 200px;
}
#submitBtn {
padding: 8px 16px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
#submitBtn:hover {
background-color: #0056b3;
}
实现交互功能
使用 JavaScript 添加事件监听器,处理用户输入和按钮点击。
document.getElementById('submitBtn').addEventListener('click', function() {
const inputValue = document.getElementById('inputField').value;
if (inputValue.trim() !== '') {
alert('You entered: ' + inputValue);
} else {
alert('Please enter some text');
}
});
添加键盘事件
为输入框添加键盘事件,允许用户通过按 Enter 键提交内容。
document.getElementById('inputField').addEventListener('keypress', function(event) {
if (event.key === 'Enter') {
document.getElementById('submitBtn').click();
}
});
动态创建 InputBox
通过 JavaScript 动态创建 InputBox 元素,适用于需要动态添加输入框的场景。
function createInputBox() {
const container = document.createElement('div');
container.className = 'input-box';
const input = document.createElement('input');
input.type = 'text';
input.placeholder = 'Enter text here';
input.id = 'dynamicInput';
const button = document.createElement('button');
button.textContent = 'Submit';
button.id = 'dynamicBtn';
container.appendChild(input);
container.appendChild(button);
document.body.appendChild(container);
button.addEventListener('click', function() {
const value = input.value;
if (value.trim() !== '') {
console.log('Submitted:', value);
}
});
}
createInputBox();
验证输入内容
添加输入验证逻辑,确保用户输入符合特定要求。
document.getElementById('submitBtn').addEventListener('click', function() {
const inputValue = document.getElementById('inputField').value;
if (inputValue.length < 5) {
alert('Input must be at least 5 characters long');
} else {
console.log('Valid input:', inputValue);
}
});
使用事件委托
对于动态生成的多个输入框,使用事件委托优化事件处理。

document.body.addEventListener('click', function(event) {
if (event.target.classList.contains('dynamic-btn')) {
const input = event.target.previousElementSibling;
console.log('Submitted:', input.value);
}
});






