This commit is contained in:
Baobhan Sith
2025-04-30 14:12:39 +08:00
parent 21f82a1df7
commit 9169d87767
2 changed files with 10 additions and 22 deletions
@@ -131,16 +131,11 @@ const scrollToSelected = async (index: number) => { // Accept index as argument
const selectedItem = listElement.children[index] as HTMLLIElement; const selectedItem = listElement.children[index] as HTMLLIElement;
if (selectedItem) { if (selectedItem) {
const listRect = listElement.getBoundingClientRect(); // 使用 scrollIntoView 使元素可见,滚动最小距离
const itemRect = selectedItem.getBoundingClientRect(); selectedItem.scrollIntoView({
behavior: 'smooth', // 可以使用 'auto' 来实现即时滚动
if (itemRect.top < listRect.top) { block: 'nearest',
// Item is above the visible area });
listElement.scrollTop -= listRect.top - itemRect.top;
} else if (itemRect.bottom > listRect.bottom) {
// Item is below the visible area
listElement.scrollTop += itemRect.bottom - listRect.bottom;
}
} }
}; };
@@ -149,18 +149,11 @@ const scrollToSelected = async (index: number) => { // Accept index as argument
const selectedItem = listElement.children[index] as HTMLLIElement; const selectedItem = listElement.children[index] as HTMLLIElement;
if (selectedItem) { if (selectedItem) {
const listRect = listElement.getBoundingClientRect(); // 使用 scrollIntoView 使元素可见,滚动最小距离
const itemRect = selectedItem.getBoundingClientRect(); selectedItem.scrollIntoView({
behavior: 'smooth', // 可以使用 'auto' 来实现即时滚动
if (itemRect.top < listRect.top) { block: 'nearest',
// Item is above the visible area });
listElement.scrollTop -= listRect.top - itemRect.top;
} else if (itemRect.bottom > listRect.bottom) {
// Item is below the visible area
listElement.scrollTop += itemRect.bottom - listRect.bottom;
}
// For smooth scrolling (optional):
// selectedItem.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
} }
}; };