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>
    </>
  );
};
相关推荐
lucky九年1 分钟前
deepseek harness主题插件dsh-web-theme
前端
FungLeo6 分钟前
成为全栈·Node 后端篇·后端工程从零搭建:TypeScript、目录与热更新
javascript·typescript·node 后端
2601_962203517 分钟前
【SpringBoot3】面向切面 AspectJ AOP 使用详解
开发语言·前端·python
XLYcmy35 分钟前
HTML/CSS/JS 基础与 Vue 技术栈深度解析
java·前端·css·html·vue3·vue2·api
新知图书1 小时前
12.3 智能体中Skill的约束与自进化实战
java·前端·数据库
风月说与山鬼1 小时前
四、Tailwind CSS——间距与尺寸
前端·css·tailwind css
en.en..1 小时前
C语言 static函数与头文件封装规范
java·c语言·前端
计算机魔术师1 小时前
旅途中用手机远程控制电脑?电脑不在身边,ToDesk/UU远程/TeamViewer移动端深度实测
前端
风月说与山鬼1 小时前
三、Tailwind CSS——排版与文字样式
前端·css·tailwind css
eokred2 小时前
图片预览组件的另一种设计:Headless、可组合、开箱即用
前端·react