在现代Web应用程序中,输入框自动完成功能,已经成为一个常见的需求。通过自动完成,用户可以更快速地输入信息,提高用户体验。
一、什么是输入框自动完成功能
输入框自动完成功能,是指在用户输入内容时,系统能够根据已有的数据源或规则,提供与输入内容相关的建议或补全选项。这样,用户在输入时,可以通过选择或点击建议项,来快速完成输入,提高输入效率和准确性。
二、实现输入框自动完成功能的基本原理
监听输入事件:通过JavaScript代码,监听输入框的输入事件,如keydown或input事件。
获取输入内容:在输入事件触发时,获取输入框的当前内容。
发送请求:将获取到的输入内容发送给后端或数据源,请求匹配的建议项。
处理响应:接收后端返回的建议项数据,解析并展示在页面上。
用户交互:用户选择或点击建议项时,将对应的建议项内容填入输入框中,完成自动完成。
三、实现输入框自动完成功能的具体步骤
下面通过一个实际案例,演示如何实现输入框自动完成功能。
案例:实现邮件地址自动补全功能
HTML
<input type="text" class="form-control" id="emailInput" placeholder="请输入邮件地址">
<ul id="suggestions"></ul>
CSS
ul, li {
margin: 0;
padding: 0;
list-style: none;
line-height: 2;
}
ul {
border: 1px solid #dddd;
}
li {
text-indent: 0.75rem;
cursor: pointer;
}
li:hover,
li.active {
background-color: rgb(55, 99, 166);
color: white;
}
Javascript
获取输入框与自动补全容器
const emailInput = document.getElementById('emailInput');
const suggestions = document.getElementById('suggestions');
监听用户输入,获取自动补全建议。
emailInput.addEventListener('input', async (event) => {
const inputContent = event.target.value.replace(/@[^@]*$/, '');
// 方式1
// 调用服务器API 获取相关数据
// 测试用例
const domains = [
'qq.com',
'163.com',
'sina.com.cn',
'outlook.com',
'gmail.com'
];
const data = domains.map(domain => (inputContent + '@' + domain));
// 渲染建议
renderSuggestions(data);
});
渲染建议,并增加选中功能。
function renderSuggestions(data) {
suggestions.innerHTML = '';
data.forEach((item) => {
const li = document.createElement('li');
li.textContent = item;
li.addEventListener('click', () => {
emailInput.value = item;
suggestions.innerHTML = '';
});
suggestions.appendChild(li);
});
}
增加键盘操作功能:上下切换选项、回车确认选项。
emailInput.addEventListener('keydown', async (event) => {
// 所有选项
const child = Array.from(suggestions.children);
// 当前选中
const activeNode = suggestions.getElementsByClassName('active');
switch (event.key) {
case 'Enter': // 选中
if (activeNode.length) {
emailInput.value = activeNode[0].innerText;
suggestions.innerHTML = '';
}
break;
case 'ArrowUp': // 向上
if (activeNode.length) {
// 已有选择项
if (activeNode[0].previousElementSibling) {
// 选择上面一个
activeNode[0].previousElementSibling.setAttribute('class', 'active');
activeNode[activeNode.length - 1].setAttribute('class', '');
}
else {
// 已选为第一个,就切换到最后一个。
child[child.length - 1].setAttribute('class', 'active');
child[0].setAttribute('class', '');
}
}
else {
// 没有选择项,默认选最后一个
child[child.length - 1].setAttribute('class', 'active');
}
break;
case 'ArrowDown': // 向下
if (activeNode.length) {
// 已有选择项
if (activeNode[0].nextElementSibling) {
// 选择下面一个
activeNode[0].nextElementSibling.setAttribute('class', 'active');
activeNode[0].setAttribute('class', '');
}
else {
// 已选为最后一个,就切换到第一个。
child[0].setAttribute('class', 'active');
child[child.length - 1].setAttribute('class', '');
}
}
else {
// 没有选择项,默认选第一个。
child[0].setAttribute('class', 'active');
}
break;
}
})
希望本文能够对您有所帮助,感谢您的阅读!
人人为我,我为人人,谢谢您的浏览,我们一起加油吧。