You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor WASM(.NET6)无JS实现列表上下键选择项

Blazor WASM 自动补全键盘操作实现(无需JS)

核心思路

通过组件内的状态变量跟踪当前选中的列表项索引,结合样式绑定标记选中项,同时处理上下键切换索引、回车键确认选择的逻辑,完全不需要依赖JavaScript。

具体实现步骤

  1. 添加状态变量
    在组件代码块中定义跟踪选中索引的变量,初始值设为-1(表示无选中项):
private List<string> SearchResults = new(); // 你的搜索结果列表
private string SearchTerm = "";
private int _selectedIndex = -1;
  1. 处理输入框键盘事件
    在输入框的onkeydown事件中捕获上下键、回车键,更新选中索引或执行选择逻辑:
<input 
    type="text" 
    @bind="@SearchTerm" 
    @onkeydown="HandleKeyDown"
    placeholder="输入搜索内容..."
/>

对应的事件处理方法:

private void HandleKeyDown(KeyboardEventArgs e)
{
    if (SearchResults.Count == 0) return;

    switch (e.Key)
    {
        case "ArrowDown":
            // 向下切换,不超过列表最后一项
            _selectedIndex = Math.Min(_selectedIndex + 1, SearchResults.Count - 1);
            break;
        case "ArrowUp":
            // 向上切换,不低于列表第一项;如果需要循环选中,可替换为:_selectedIndex = _selectedIndex <= 0 ? SearchResults.Count - 1 : _selectedIndex - 1;
            _selectedIndex = Math.Max(_selectedIndex - 1, 0);
            break;
        case "Enter":
            if (_selectedIndex >= 0)
            {
                SelectItem(SearchResults[_selectedIndex]);
                _selectedIndex = -1; // 选中后重置索引
            }
            break;
    }
}

private void SelectItem(string item)
{
    // 你的选中逻辑,比如把选中项赋值给输入框、关闭下拉列表等
    SearchTerm = item;
    // 可添加隐藏下拉列表的逻辑,比如绑定IsDropdownVisible变量控制显示
}
  1. 标记选中的列表项
    渲染搜索结果列表时,通过@class绑定给当前选中项添加高亮样式:
@if (SearchResults.Any())
{
    <ul class="autocomplete-list">
        @for (int i = 0; i < SearchResults.Count; i++)
        {
            var index = i;
            var item = SearchResults[i];
            <li 
                class="@(_selectedIndex == index ? "selected-item" : "")"
                @onclick="() => SelectItem(item)"
                @onmouseover="() => _selectedIndex = index"
            >
                @item
            </li>
        }
    </ul>
}
  1. 添加高亮样式
    在组件的<style>标签或全局样式表中定义选中项的样式:
.autocomplete-list {
    list-style: none;
    padding: 0;
    border: 1px solid #ddd;
    border-top: none;
}

.autocomplete-list li {
    padding: 8px 12px;
    cursor: pointer;
}

.selected-item {
    background-color: #007bff;
    color: white;
}

关键细节

  • 鼠标悬停时同步更新_selectedIndex,保证键盘和鼠标交互的一致性;
  • 回车键逻辑中判断_selectedIndex有效性,避免空选择;
  • 可根据需求实现循环选中(上下键到达边界后跳转到另一端),提升用户体验。

内容的提问来源于stack exchange,提问作者Geo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 15:45:11