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>
    </>
  );
};
相关推荐
Blanche15007 分钟前
利用 RAG 为答疑机器人扩展知识范围
前端
天若有情67313 分钟前
【纯前端小工具】公历生日转农历,批量查询每年农历生日对应的公历日期(GitHub Pages在线直接用)
前端·javascript·github pages·农历转换·lunisolar·网页小工具
SoonITer14 分钟前
怎样构建一个 Agent-friendly 的网站
前端·agent
颜进强29 分钟前
01 · NestJS 是什么:用途、解决什么问题、与热门框架对比
前端·后端·ai编程
wendZzoo33 分钟前
前端工程师的 3D 第一课:一个模型如何进入网页
前端
颜进强44 分钟前
04 · NestJS 依赖注入:你在 `@Module` 写的 providers,和构造参数里那个类型,是怎么"对上"的?
前端·后端·ai编程
肆仲冬1 小时前
不用框架,用 TypeScript 从零搭一个 Agent 框架
前端
林语琛1 小时前
我写的 switch…break 被 Babel 偷偷吞了
前端·javascript·babel
烈风逍遥1 小时前
第六篇:RAG 知识库构建与检索全链路
前端·人工智能·后端
爱丶不疚1 小时前
什么是 Jev 决策模型?它适合干什么?
前端·agent