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>
    </>
  );
};
相关推荐
亿元程序员16 分钟前
Creator都快4.0了,怎么能没有这样的功能?
前端
q***649717 分钟前
SpringMVC 请求参数接收
前端·javascript·算法
万少21 分钟前
流碧卡片 6 小时闪电开发 AI gemini-3-pro-preview ! 秒出小红书爆款图,免下载直接用
前端·后端·ai编程
向葭奔赴♡32 分钟前
若依系统权限控制全流程解析
前端·javascript·vue.js·ruoyi·navicat
IT_陈寒40 分钟前
Python开发者必知的5个高效技巧,让你的代码性能提升50%
前端·人工智能·后端
u***u68542 分钟前
Vue虚拟现实案例
前端·vue.js·vr
q***96581 小时前
springboot3整合knife4j详细版,包会!(不带swagger2玩)
android·前端·后端
艾小码1 小时前
Vue 3 defineProps 与 defineEmits 深度解析
前端·javascript·vue.js
前端炒粉4 小时前
35.LRU 缓存
开发语言·javascript·数据结构·算法·缓存·js
巧克力芋泥包5 小时前
前端使用阿里云图形验证码;并且与安卓进行交互
android·前端·阿里云