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>
    </>
  );
};
相关推荐
Sapphire~16 分钟前
重学前端003 --- CSS 颜色
前端·css
慧一居士17 分钟前
CSS和CSS3区别对比
前端·css3
我血条子呢17 分钟前
动态组件和插槽
前端·javascript·vue.js
中微子25 分钟前
RESTful架构与前后端路由演进:构建现代化Web应用的核心规范
前端
前端付豪26 分钟前
13、表格系统架构:列配置、嵌套数据、复杂交互
前端·javascript·架构
南屿im31 分钟前
发布订阅模式和观察者模式傻傻分不清?一文搞懂两大设计模式
前端·javascript
I_have_a_lemon32 分钟前
前端、产品、设计师神器推荐——Onlook
前端·cursor
前端小巷子33 分钟前
深入解析CSRF攻击
前端·安全·面试
JustHappy34 分钟前
SPA?MPA?有啥关系?有啥区别?聊一聊页面形态 or 路由模式
前端·javascript·架构
每天开心34 分钟前
🧙‍♂️闭包应用场景之--防抖和节流
前端·javascript·面试