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>
    </>
  );
};
相关推荐
崽崽的谷雨7 小时前
react使用ag-grid及常用api笔记
笔记·react.js·ag-grid
excel7 小时前
Vue 模板解析器 parserOptions 深度解析
前端
前端小咸鱼一条8 小时前
17.React获取DOM的方式
前端·javascript·react.js
excel8 小时前
Vue 编译核心中的运行时辅助函数注册机制详解
前端
excel8 小时前
🌿 深度解析 Vue DOM 编译器模块源码:compile 与 parse 的构建逻辑
前端
excel8 小时前
深度解析 Vue 编译器中的 transformShow:v-show 指令的编译原理
前端
excel8 小时前
深度解析:decodeHtmlBrowser —— 浏览器端 HTML 解码函数设计
前端
excel8 小时前
深度解析:Vue 模板编译器中的 transformVText 实现原理
前端
excel8 小时前
深度解析:isValidHTMLNesting —— HTML 嵌套合法性验证的设计与实现
前端
冴羽8 小时前
看了下昨日泄露的苹果 App Store 源码……
前端·javascript·svelte