React实现Input聚焦时背景模糊效果(使用Material UI)
实现Material UI输入框聚焦时页面背景模糊效果
不需要使用额外库,仅通过Material UI组件结合React状态管理或CSS伪类就能实现该效果。以下是具体实现方案:
方案一:React状态控制(更灵活)
通过监听输入框的onFocus和onBlur事件,切换背景的模糊状态:
import { useState } from 'react'; import TextField from '@mui/material/TextField'; import { Box } from '@mui/material'; export default function BlurOnFocusInput() { const [isInputFocused, setIsInputFocused] = useState(false); return ( <Box sx={{ width: '100vw', height: '100vh', position: 'relative', backgroundImage: 'url(你的背景图路径)', // 替换为实际背景图 backgroundSize: 'cover', transition: 'filter 0.3s ease-in-out', // 添加过渡动画 filter: isInputFocused ? 'blur(8px)' : 'none', }} > {/* 输入框容器,层级高于背景 */} <Box sx={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', zIndex: 1, }} > <TextField label="请输入内容" variant="outlined" onFocus={() => setIsInputFocused(true)} onBlur={() => setIsInputFocused(false)} sx={{ bgcolor: 'white', px: 1, borderRadius: 1, }} /> </Box> </Box> ); }
方案二:纯CSS伪类实现(无JS逻辑)
利用CSS的:focus-within伪类,当输入框容器内有元素聚焦时,触发背景模糊:
import TextField from '@mui/material/TextField'; import { Box } from '@mui/material'; export default function CSSBlurInput() { return ( <Box sx={{ width: '100vw', height: '100vh', position: 'relative' }}> {/* 输入框容器 */} <Box className="input-container" sx={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', zIndex: 1, }}> <TextField label="请输入内容" variant="outlined" sx={{ bgcolor: 'white', px: 1, borderRadius: 1 }} /> </Box> {/* 背景层 */} <Box className="background-layer" sx={{ width: '100%', height: '100%', backgroundImage: 'url(你的背景图路径)', backgroundSize: 'cover', transition: 'filter 0.3s ease-in-out', }} /> {/* 全局样式 */} <style jsx global>{` .input-container:focus-within ~ .background-layer { filter: blur(8px); } `}</style> </Box> ); }
关键说明
- 核心通过CSS的
filter: blur(数值)实现背景模糊效果,配合transition添加平滑过渡动画 - 两种方案都无需额外依赖,完全基于Material UI和原生React/CSS能力实现
- 若背景是页面已有内容而非图片,可将模糊效果应用到内容容器上,输入框保持高层级显示
内容的提问来源于stack exchange,提问作者Terhebat Hokage
相关产品推荐
相关产品推荐

