- 使用Virtualize组件来显示表格并启用虚拟滚动:
- 使用JavaScriptInterop来调用JavaScript方法实现定位特定键值和检测可见项:
@inject IJSRuntime jsRuntime
@code {
Dictionary items = new Dictionary
{
{ "Item1", "Value1" },
{ "Item2", "Value2" },
{ "Item3", "Value3" },
{ "Item4", "Value4" },
//...
};
async Task ScrollToItem()
{
string key = "Item3";
int index = 0;
foreach (var item in items)
{
if (item.Key == key)
{
break;
}
index++;
}
await jsRuntime.InvokeVoidAsync("scrollToItem", index);
}
}
- 在JavaScript文件中实现滚动到指定项和检测可见项的方法:
function scrollToItem(index) {
const itemList = document.getElementById("itemList");
const itemHeight = 30;
const scrollTop = index * itemHeight;
itemList.scrollTop = scrollTop;
const visibleItems = getVisibleItems(itemList);
console.log(visibleItems);
}
function getVisibleItems(container) {
const scrollTop = container.scrollTop;
const itemHeight = 30;
const startIndex = Math.floor(scrollTop / itemHeight);
const endIndex = Math.min(Math.ceil((scrollTop + container.clientHeight) / itemHeight), container.childElementCount);
const visibleItems = [];
for (let i = startIndex;