You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Material-UI按钮鼠标悬停边框长度动画效果实现问题

实现Material-UI按钮悬停时的边框长度动画

要实现示例中的边框长度动画,不能直接给元素添加border属性,而是需要通过**四条独立的边框元素(伪元素+内嵌span)**分别做宽度/高度的过渡动画,在鼠标悬停时依次展开。以下是修改后的完整实现:

1. 调整按钮的样式定义

const ImageButton = styled(ButtonBase)(({ theme }) => ({
  position: "relative",
  height: 200,
  [theme.breakpoints.down("sm")]: {
    width: "100% !important",
    height: 100,
  },
  "&:hover, &.Mui-focusVisible": {
    zIndex: 1,
    "& .MuiImageBackdrop-root": {
      opacity: 0.15,
    },
    "& .MuiImageMarked-root": {
      opacity: 0,
    },
    // 移除原有的border设置,改为触发Typography内的边框动画
    "& .MuiTypography-root": {
      color: theme.palette.primary.main, // 可选:hover时同步改变文字颜色
    },
  },
}));

2. 重构Typography组件的边框动画逻辑

<Typography
  component="span"
  variant="subtitle1"
  color="inherit"
  sx={{
    position: "relative",
    p: 4,
    pt: 2,
    pb: (theme) => `calc(${theme.spacing(1)} + 6px)`,
    // 定义四条边框的基础样式
    "&::before, &::after, & .border-bottom, & .border-left": {
      content: '""',
      position: "absolute",
      background: "currentColor",
      transition: "all 0.3s ease",
    },
    // 上边:初始宽度0,hover时铺满
    "&::before": {
      top: 0,
      left: 0,
      width: "0%",
      height: "4px",
      transitionDelay: "0s",
    },
    // 右边:初始高度0,hover时铺满
    "&::after": {
      top: 0,
      right: 0,
      width: "4px",
      height: "0%",
      transitionDelay: "0.1s",
    },
    // 下边:初始宽度0,hover时铺满
    "& .border-bottom": {
      bottom: 0,
      right: 0,
      width: "0%",
      height: "4px",
      transitionDelay: "0.2s",
    },
    // 左边:初始高度0,hover时铺满
    "& .border-left": {
      bottom: 0,
      left: 0,
      width: "4px",
      height: "0%",
      transitionDelay: "0.3s",
    },
    // 悬停时触发动画
    "&:hover::before, &:hover .border-bottom": {
      width: "100%",
    },
    "&:hover::after, &:hover .border-left": {
      height: "100%",
    },
  }}
>
  <ImageMarked className="MuiImageMarked-root" />
  {/* 新增两个span用于下边和左边的边框 */}
  <span className="border-bottom" />
  <span className="border-left" />
</Typography>

关键说明

  • 通过给四条边框设置不同的transitionDelay,实现了从上→右→下→左的依次展开动画,和示例效果一致
  • 边框颜色使用currentColor,会继承Typography的文字颜色,确保样式统一
  • 可以调整transition的时长(比如把0.3s改成0.5s)和缓动函数(比如ease-in-out)来修改动画节奏
  • 若不需要分步动画,移除所有transitionDelay即可让四条边框同时展开

内容的提问来源于stack exchange,提问作者Jorge Leonardo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 16:32:40