menu item scroll problem in mobile fixed

This commit is contained in:
2025-11-10 11:21:44 +08:00
parent 671b0de875
commit 3530f6d52e

View File

@@ -78,19 +78,15 @@ function Header({ showMenu = false }: HeaderProps) {
const element = isOnMainPage ? document.getElementById(targetId) : null;
if (element) {
// Safari-compatible scrolling with fallback
const headerOffset = headerHeight || 0;
const elementPosition = element.getBoundingClientRect().top;
const offsetPosition = elementPosition + window.pageYOffset - headerOffset;
try {
window.scrollTo({
top: offsetPosition,
behavior: 'smooth'
});
} catch (e) {
// Fallback for older Safari versions
window.scrollTo(0, offsetPosition);
// Close drawer first, then scroll after animation completes
if (isDrawerOpen) {
setIsDrawerOpen(false);
// Wait for drawer animation to complete (300ms) before scrolling
setTimeout(() => {
performScroll(element);
}, 350);
} else {
performScroll(element);
}
return;
}
@@ -105,6 +101,31 @@ function Header({ showMenu = false }: HeaderProps) {
}
};
const performScroll = (element: HTMLElement) => {
// Safari and mobile-compatible scrolling with multiple fallbacks
const headerOffset = headerHeight || 0;
const elementPosition = element.getBoundingClientRect().top;
const offsetPosition = elementPosition + (window.pageYOffset || window.scrollY || document.documentElement.scrollTop) - headerOffset;
// Try smooth scrolling first
try {
window.scrollTo({
top: offsetPosition,
behavior: 'smooth'
});
} catch (e) {
// Fallback 1: Try scrollTo without behavior
try {
window.scrollTo(0, offsetPosition);
} catch (e2) {
// Fallback 2: Use element.scrollIntoView
const yOffset = -headerOffset;
const y = element.getBoundingClientRect().top + window.pageYOffset + yOffset;
window.scrollTo({ top: y, behavior: 'smooth' });
}
}
};
const handleMenuClick = (itemId: string) => {
if (itemId === 'recipes') {
const isOnRecipePage = location.pathname === '/recipe';
@@ -119,10 +140,9 @@ function Header({ showMenu = false }: HeaderProps) {
window.location.href = '/recipe';
return;
} else {
// Scroll to section (drawer will be closed inside scrollToSection)
scrollToSection(itemId);
}
setIsDrawerOpen(false);
};
const menuItems = [