使用固定标题,导航栏上的链接会被赋予一个偏移值,以便它滚动到该部分的开头并且可见。它在较大的屏幕上工作正常,但在较小的屏幕上,它不起作用。在较小的屏幕上,它的滚动远远超出了该部分的开头,甚至超过了固定标题的高度。
function Header() {
const [menuAnchor, setMenuAnchor] = useState(null);
const [offset, setOffset] = useState(-90); // Default offset
const openMenu = (event) => {
setMenuAnchor(event.currentTarget);
};
const closeMenu = () => {
setMenuAnchor(null);
};
const pages = ['About', 'Skills', 'Projects', 'Contact'];
useEffect(() => {
const handleResize = () => {
if (window.innerWidth <= 768) {
// Adjust the offset for smaller screens
setOffset(-120);
} else {
// Default offset for larger screens
setOffset(-90);
}
};
// Set initial offset
handleResize();
// Update offset on window resize
window.addEventListener('resize', handleResize);
// Clean up the event listener
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);
return (
<AppBar
className='navbar'
position="fixed"
style={{ backgroundColor: 'white' }}
sx={{ height: '90px', display: 'flex', justifyContent: 'center' }}
>
<Container maxWidth="xl">
<Box sx={{ display: 'flex', alignItems: 'center' }}>
<Box sx={{ flexGrow: 1, display: { xs: 'none', md: 'flex' } }}>
{pages.map((page, index) => (
<Button
key={index}
sx={{ mx: 2, color: 'black'}}
>
<Link to={page.toLowerCase()} smooth={true} duration={500} offset={offset}>
{page}
</Link>
</Button>
))}
</Box>
<Box sx={{ display: { xs: 'block', md: 'none' } }}>
<IconButton
edge="end"
color="black"
aria-label="menu"
onClick={openMenu}
>
<MenuIcon />
</IconButton>
<Menu
anchorEl={menuAnchor}
open={Boolean(menuAnchor)}
onClose={closeMenu}
>
{pages.map((page, index) => (
<MenuItem
key={index}
onClick={() => {
closeMenu();
document
.getElementById(page.toLowerCase())
.scrollIntoView({ behavior: 'smooth', block: 'center' });
}}
>
{page}
</MenuItem>
))}
</Menu>
</Box>
</Box>
</Container>
</AppBar>
);
}
它适用于较大的屏幕,但为什么它不适用于较小的屏幕。
我尝试过将 window.innerwidth 作为设置偏移值的条件,但仍然不起作用。
您找到问题的答案了吗?我也有兴趣。