react mui textfield marquee 跑马灯效果实现

网上找了一圈包括stackoverflow, 也没有找到mui textfield marquee的实现方式,结合gpt实现了下,效果是,如果这个文字不超过textfield本身,则不滚动,否则在鼠标悬浮的时候滚动,并且滚动的距离应该是比较恰到好处的

用法如下: text是你需要填写的文字

还可以再封装下比如一些style什么的..

TypeScript 复制代码
<MarqueeTypography> text </MarqueeTypography>
TypeScript 复制代码
import React, { useRef, useState, useEffect } from 'react';
import { Typography, GlobalStyles } from '@mui/material';

const MarqueeTypography = ({ children }) => {
  const textRef = useRef(null);
  const [isOverflowing, setIsOverflowing] = useState(false);
  const [distance, setDistance] = useState(0);

  useEffect(() => {
    if (textRef.current) {
      const textWidth = textRef.current.scrollWidth;
      const containerWidth = textRef.current.clientWidth;
      const newDistance = textWidth - containerWidth;
      setIsOverflowing(textWidth > containerWidth);
      if (newDistance !== distance) {
        setDistance(newDistance);
      }
    }
  }, [distance, children]);

  return (
    <>
      <GlobalStyles
        styles={{
          '@keyframes marquee': {
            '0%': { transform: 'translateX(0%)' },
            '100%': { transform: `translateX(-${distance}px)` },
          },
        }}
      />
      <Typography
        fontSize={'14px'}
        ref={textRef}
        sx={{
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textOverflow: 'ellipsis',
          '&:hover': {
            overflow: 'visible',
            textOverflow: 'clip',
            whiteSpace: 'nowrap',
            animation: isOverflowing ? `marquee 3s linear infinite` : 'none',
          },
        }}
      >
        {children}
      </Typography>
    </>
  );
};
相关推荐
小满zs9 分钟前
Next.js精通SEO第二章(robots.txt + sitemap.xml)
前端·seo
kyriewen13 分钟前
你的首屏慢得像蜗牛?这6招让页面“秒开”
前端·面试·性能优化
算是难了35 分钟前
Nestjs学习总结_3
前端·typescript·node.js
yogalin19931 小时前
如何实现一个简化的响应式系统
前端
kyriewen111 小时前
项目做了一半想重写?这套前端架构让你少走3年弯路
前端·javascript·chrome·架构·ecmascript·html5
HashTang1 小时前
我用 Cloudflare Workers + GitHub Actions 做了个 2.5 刀/月的 AI 日报,代码开源了
前端·ai编程·aiops
老王以为1 小时前
前端重生之 - 前端视角下的 Python
前端·后端·python
饭后一颗花生米1 小时前
2026 AI加持下前端学习路线:从入门到进阶,高效突破核心竞争力
前端·人工智能·学习
五号厂房1 小时前
TypeScript 类型导入详解:import type 与 import {type}
前端
果然_2 小时前
为什么你的 PR 总是多出一堆奇怪的 commit?90% 的人都踩过这个 Git 坑
前端·git