You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+MUI环境下自定义输入框光标样式与动画的技术咨询

React + MUI 自定义输入框光标样式与动画解决方案

一、禁用默认光标闪烁/自定义闪烁速度

浏览器默认光标闪烁没有直接可修改速度的CSS属性,自定义动画还会和默认闪烁冲突,最稳妥的解决方式是隐藏默认光标,用伪元素模拟自定义光标:

  • 第一步:用caret-color: transparent隐藏原生光标
  • 第二步:给输入框添加伪元素,自定义光标样式和闪烁动画

原生 input 示例

.custom-input {
  caret-color: transparent; /* 隐藏默认光标 */
  position: relative;
  padding-right: 20px; /* 给模拟光标预留空间 */
}

.custom-input::after {
  content: '';
  position: absolute;
  top: 50%;
  right: 8px; /* 调整位置匹配输入框内边距 */
  transform: translateY(-50%);
  width: 2px;
  height: 70%;
  background-color: #1890ff; /* 自定义光标颜色 */
  animation: blink 1.2s infinite; /* 1.2s就是自定义的闪烁速度 */
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0; }
}

React 中使用:

<input className="custom-input" autocomplete="off" />

MUI TextField 示例

MUI 的 TextField 是封装组件,通过 sx 注入样式即可:

import TextField from '@mui/material/TextField';

<TextField
  sx={{
    '& input': {
      caretColor: 'transparent',
      position: 'relative',
      paddingRight: '24px',
      '&::after': {
        content: '""',
        position: 'absolute',
        top: '50%',
        right: '12px', // 匹配MUI输入框默认内边距
        transform: 'translateY(-50%)',
        width: '3px',
        height: '75%',
        backgroundColor: '#ff4d4f',
        animation: 'blink 0.8s infinite',
      },
    },
    // 直接在sx里定义keyframes
    '@keyframes blink': {
      '0%, 50%': { opacity: 1 },
      '51%, 100%': { opacity: 0 },
    },
  }}
  label="自定义光标输入框"
  autocomplete="off"
/>

二、修改光标宽度

完全不需要替换特殊字符,用上面的伪元素模拟方式,直接调整伪元素的 width 属性就能控制光标宽度(比如示例里的3px),还能自由调整高度、圆角等样式,比替换特殊字符的方式灵活得多。

内容的提问来源于stack exchange,提问作者ewakwwg12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 04:45:38