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>
    </>
  );
};
相关推荐
QT 小鲜肉13 小时前
【Linux命令大全】001.文件管理之mc命令(实操篇)
linux·运维·服务器·前端·笔记
ttod_qzstudio13 小时前
备忘录之事件监听器绑定陷阱:为什么 .bind(this) 会移除失败?
javascript·typescript·内存泄漏·事件监听
土豆_potato13 小时前
AI深度思考到底开不开
前端·aigc
ohyeah13 小时前
React 中的跨层级通信:使用 Context 实现主题切换功能
前端·react.js
winfredzhang14 小时前
打造专属桌面时钟:纯HTML实现的全功能动态时钟
前端·html·农历·生肖·周次
哥本哈士奇14 小时前
使用Gradio构建AI前端 - RAG的QA模块
前端·人工智能·状态模式
扶我起来还能学_14 小时前
Vue3 proxy 数据响应式的简单实现
前端·javascript·vue
Dragon Wu14 小时前
前端项目架构 项目格式化规范篇
前端·javascript·react.js·前端框架
QQ 313163789014 小时前
文华财经软件指标公式期货买卖信号提示软件
java·前端·javascript
狂龙骄子14 小时前
svg实现蚂蚁线动画
javascript·蚂蚁线动画·蚂蚁线·虚线动画