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

寻找Material UI中实现未登录用户半段文章渐隐隐藏的组件

实现Material UI风格的文章内容渐变遮罩(登录解锁完整内容)

你说的这个效果并非Material UI的现成组件,而是用线性渐变遮罩配合基础组件实现的常见方案,很多教程会用这个方式做登录解锁内容的引导。

核心实现思路

给未登录用户的文章内容底部添加一个从透明过渡到页面背景色的渐变遮罩,让内容看起来逐渐“消失”,登录后移除遮罩即可显示完整内容。

代码示例(基于Material UI v5)

import { Box, Typography, Button } from '@mui/material';
import { useState } from 'react';

const BlogPost = () => {
  // 模拟登录状态,实际项目中从全局状态/接口获取
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  return (
    <Box sx={{ position: 'relative', maxWidth: 800, margin: '0 auto', padding: 2 }}>
      {/* 文章内容 */}
      <Typography variant="body1" paragraph>
        这里是文章的开头内容,所有访客都可以正常阅读,比如介绍文章主题的引子部分...
      </Typography>
      <Typography variant="body1" paragraph>
        接下来是文章的核心内容片段,未登录用户能看到一部分,但后面会被渐变遮罩覆盖...
      </Typography>
      <Typography variant="body1" paragraph>
        这部分是需要登录才能查看的完整内容,未登录状态下会被遮罩隐藏,比如深度分析、独家观点之类的...
      </Typography>
      <Typography variant="body1" paragraph>
        更多后续内容,只有登录后才能全部浏览到...
      </Typography>

      {/* 未登录时显示渐变遮罩和登录按钮 */}
      {!isLoggedIn && (
        <>
          <Box
            sx={{
              position: 'absolute',
              bottom: 0,
              left: 0,
              right: 0,
              height: '150px',
              // 渐变从透明过渡到页面背景色(这里用白色,可根据你的主题调整)
              background: 'linear-gradient(to bottom, rgba(255,255,255,0), rgba(255,255,255,1))',
              pointerEvents: 'none', // 不影响用户选中可见的文本内容
            }}
          />
          <Box sx={{ textAlign: 'center', marginTop: 3 }}>
            <Button variant="contained" onClick={() => setIsLoggedIn(true)}>
              登录查看完整内容
            </Button>
          </Box>
        </>
      )}
    </Box>
  );
};

export default BlogPost;

关键细节说明

  • 父容器设置position: relative,让遮罩可以绝对定位在内容底部
  • 渐变遮罩的高度可以根据你想隐藏的内容长度调整,数值越大隐藏越多
  • pointerEvents: none是为了让用户能正常选中、复制可见的文本,不会被遮罩挡住
  • 实际项目中,isLoggedIn状态应该从全局状态(比如Redux、Context)或后端接口获取,而不是本地模拟

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 23:30:27