Material UI头像悬停显示卡片功能异常求助
解决方案
你的问题出在两个核心点:Card默认未隐藏,且hover事件绑定在了Card自身而非头像的容器上。下面是修复后的代码及说明:
import { Avatar, Card, CardContent, Typography } from '@mui/material'; import { Container } from '@mui/system'; import { ReactElement } from 'react'; export const Test = (): ReactElement => { const users = [{ login: 'sally' }, { login: 'john' }]; return ( <> <Container sx={{ display: 'flex', flexDirection: 'row', justifyContent: 'center', alignItems: 'center', border: 'solid 1px', p: 2 }}> {users.map((user) => ( <div key={user.login} sx={{ display: 'inline-block', marginRight: 10, position: 'relative', // 父容器悬停时控制Card显示 '&:hover .user-card': { display: 'block' } }} > <Avatar alt={`Badge photo for ${user.login}`} src={`https://mywebpage?uid=${user.login}`} sx={{ height: 40, width: 40, m: 2 }} /> <Card className="user-card" sx={{ height: '400px', width: '500px', position: 'absolute', top: 0, left: '100%', ml: 2, display: 'none', // 默认隐藏 boxShadow: 10, '&:hover': { boxShadow: 20, }, }} > <CardContent> <Typography>{user.login}</Typography> </CardContent> </Card> </div> ))} </Container> </> ); };
关键修改说明:
- 给包裹Avatar和Card的父容器添加
position: relative,为Card的绝对定位提供参考基准,避免Card乱跑。 - Card默认设置
display: none,通过父容器的&:hover .user-card选择器,实现悬停头像时显示Card的效果。 - 将Card设为
position: absolute,脱离文档流,避免默认隐藏状态被打乱页面布局,同时可以通过top、left控制它相对于头像的位置。 - 修正了Container的
direction属性为flexDirection(Material UI的sx语法中,flex布局方向用flexDirection而非direction)。
内容的提问来源于stack exchange,提问作者PandasM
相关产品推荐
相关产品推荐

