如何在不支持datalist的CefSharp中用JS模拟其输入联想功能?
模拟datalist实现支持自由输入+实时联想的输入框
可以用纯JavaScript配合HTML/CSS完全模拟datalist的核心行为,同时保留自由输入的能力,以下是完整实现:
实现代码
HTML结构
<!-- 输入框 --> <input type="text" id="customInput" placeholder="输入关键词..."> <!-- 自定义下拉联想列表 --> <ul id="suggestionList" class="suggestion-list"></ul>
CSS样式
#customInput { padding: 8px 12px; width: 300px; border: 1px solid #ccc; border-radius: 4px; font-size: 14px; } .suggestion-list { position: absolute; list-style: none; margin: 2px 0 0 0; padding: 0; width: 300px; border: 1px solid #ccc; border-radius: 4px; background: white; box-shadow: 0 2px 4px rgba(0,0,0,0.1); display: none; max-height: 200px; overflow-y: auto; } .suggestion-list li { padding: 8px 12px; cursor: pointer; } .suggestion-list li:hover { background-color: #f0f0f0; }
JavaScript逻辑
// 预设的联想选项数组 const suggestions = [ "red onion", "yellow pepper", "green bean", "red apple", "purple cabbage" ]; const input = document.getElementById('customInput'); const suggestionList = document.getElementById('suggestionList'); // 监听输入事件,实时过滤选项 input.addEventListener('input', function() { const inputValue = this.value.toLowerCase(); // 清空现有列表 suggestionList.innerHTML = ''; if (!inputValue) { suggestionList.style.display = 'none'; return; } // 过滤匹配的选项:包含输入的任意关键词(不区分大小写) const matchedSuggestions = suggestions.filter(item => item.toLowerCase().includes(inputValue) ); if (matchedSuggestions.length === 0) { suggestionList.style.display = 'none'; return; } // 生成匹配的列表项 matchedSuggestions.forEach(item => { const li = document.createElement('li'); li.textContent = item; // 点击列表项填充到输入框 li.addEventListener('click', function() { input.value = this.textContent; suggestionList.style.display = 'none'; }); suggestionList.appendChild(li); }); suggestionList.style.display = 'block'; }); // 点击页面其他区域关闭联想列表 document.addEventListener('click', function(e) { if (!input.contains(e.target) && !suggestionList.contains(e.target)) { suggestionList.style.display = 'none'; } });
关键特性说明
- 自由输入支持:输入框完全允许用户输入任意内容,不受预设选项限制
- 实时模糊匹配:不管输入的是选项中的开头词(如"red"匹配"red onion"、"red apple")还是中间词(如"onion"匹配"red onion"),都能精准筛选出结果
- 交互体验:鼠标悬浮列表项有高亮效果,点击选项自动填充输入框,点击外部自动关闭列表
- 兼容性:纯原生实现,完全适配CefSharp环境,不需要依赖任何框架
内容的提问来源于stack exchange,提问作者Tyler N
相关产品推荐
相关产品推荐

