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>
    </>
  );
};
相关推荐
杉氧13 分钟前
Flutter 跨平台多端适配与 Android/iOS 一键自动化打包发布
android·前端·flutter
障碍的枫子13 分钟前
xss和CSRF的攻击和防御
前端·xss·csrf
用户9210802628621 分钟前
3. 给 Bubble 新增一个 Agent Variant
前端
抓不住时间的沙24 分钟前
butterfly主题美化,打造属于自己的个性博客
java·开发语言·前端·javascript·node.js·github
kyriewen35 分钟前
前端切图仔被 AI 新闻淹死的第 N 天,我用 TRAE Work 定时任务救了自己
前端·人工智能·trae
京东云开发者36 分钟前
【全栈实践】第一个 AI Agent 项目:从零搭建 AI 音频创作助手(高级篇)
前端·agent·音视频开发
AbrahamCS1 小时前
从角色协同到可运行图:Graph Engineer 与多智能体编排
前端·人工智能·智能体
BigTopOne1 小时前
VS Code IntelliSense 配置(解决 #include 找不到的报红)
前端
愚公搬代码1 小时前
【愚公系列】《Web应用安全》005-Visual Studio Code编辑器的使用
前端·安全·编辑器
用户921080262861 小时前
2. 以 Bubble 为例,看 Ant Design X Vue 组件是怎么设计的
前端