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>
    </>
  );
};
相关推荐
妖精的羽翼6 分钟前
前端(Vue)→ 全栈 + AI 应用开发
前端
码路飞25 分钟前
玩了一圈 AI 编程工具,Background Agent 才是让我真正震撼的东西
前端·javascript
UCloud_TShare28 分钟前
优刻得发布云搜索服务CSS:面向AI时代的企业级搜索基础设施
前端·css·人工智能
林恒smileZAZ35 分钟前
Three.js实现更真实的3D地球[特殊字符]动态昼夜交替
开发语言·javascript·3d
月月大王的3D日记37 分钟前
别再复制粘贴了,从零拆解 3D 场景的诞生过程
javascript
木斯佳42 分钟前
前端八股文面经大全:字节暑期前端一面(2026-04-21)·面经深度解析
前端·面试·校招·面经·实习
昭昭日月明1 小时前
前端仔速通 Python
javascript·python
SailingCoder1 小时前
Electron 安全IPC核心:contextBridge 安全机制
javascript·安全·electron
Jolyne_1 小时前
前端从0开始的LangChain学习(一)
前端·langchain
掘金一周1 小时前
掘友们,一人说一个你买过夯到爆的东西 | 沸点周刊 4.23
前端·人工智能·后端