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>
    </>
  );
};
相关推荐
敲代码的玉米C3 分钟前
Agent 做 IDE
前端·人工智能·开源
鹏北海3 分钟前
AI 全栈时代的多语言 SDK 版本管理:认识 mise
前端·后端
下山3 分钟前
别再手切终端管 Agent 了!1 个 Skill 监督多个主流 CLI,默认每 15 秒读屏(建议收藏)🚀
前端·ai编程
飘逸啊4 分钟前
分而治之:关注点分离在Android与React中的架构实践与对比
前端
算法解题那些事4 分钟前
前端暑期实习面经(网上收集)
前端
敲代码的玉米C5 分钟前
补 322 个测试,挖出 19 个 bug
前端·人工智能·架构
敲代码的玉米C6 分钟前
怎么让 Agent 没法假装自己成功了
前端·人工智能·架构
不好听61333 分钟前
React useContext:跨层级共享数据的上下文
react.js
涛涛ing33 分钟前
狂揽2.4万星标:一行命令,AI会自己找技能了
前端
Csvn34 分钟前
🚨 JSON.stringify 的 6 个隐藏坑:为什么你的数据序列化后"消失"了?
前端