实现下拉菜单在用户输入时自动滚动到第一个匹配选项
实现下拉菜单在用户输入时自动滚动到第一个匹配选项
嘿,我看了你的代码,现在已经能正确高亮第一个匹配的国家选项了,要实现自动滚动到这个选项其实很简单,只需要在你标记第一个匹配项的地方,加上滚动逻辑就行~另外我还发现了一个小问题:你每次调用filtrar函数时,都会给所有下拉选项重复绑定click事件,这会导致点击一次触发多次回调,最好把事件绑定移到函数外面,避免重复绑定。
修改后的JavaScript代码
// 提前获取元素,避免重复查询 const countries = document.querySelectorAll('.dropdown-item'); const inputs = document.getElementById('country'); // 只绑定一次click事件,不要放在filtrar函数里 countries.forEach(item => { item.addEventListener("click", function(e) { inputs.value = item.textContent; }); }); function filtrar() { const input = inputs.value.trim(); const inputlow = input.toLowerCase(); const regex = new RegExp(`^${inputlow}`, 'i'); let found = false; let firstMatchItem = null; countries.forEach(item => { const itemtext = item.textContent.toLowerCase(); if (found || inputlow.length === 0) { item.classList.remove('selected-country'); } else if (regex.test(itemtext)) { item.classList.add('selected-country'); found = true; firstMatchItem = item; // 保存第一个匹配的元素 } else { item.classList.remove('selected-country'); } }); // 如果找到第一个匹配项,就滚动到它的位置 if (firstMatchItem) { // 使用scrollIntoView,配置平滑滚动并对齐到顶部 firstMatchItem.scrollIntoView({ behavior: 'smooth', block: 'start' }); } }
代码修改说明
- 把
click事件绑定移到了filtrar函数外面,确保每个选项只绑定一次点击事件,避免重复触发的问题。 - 在找到第一个匹配的选项时,把它保存到
firstMatchItem变量中。 - 遍历结束后,如果存在匹配项,调用
scrollIntoView()方法让它滚动到可视区域,behavior: 'smooth'可以实现平滑滚动效果,block: 'start'让元素对齐到滚动容器的顶部。
额外提示
你的下拉菜单样式里设置了max-height:300%;,这个值有点奇怪,建议改成具体的像素值比如max-height: 300px;,这样滚动容器的高度更可控,滚动效果也会更稳定。
备注:内容来源于stack exchange,提问作者new221
相关产品推荐
相关产品推荐

