Blazor .NET 8实现类Facebook/StackOverflow式通知弹窗方案问询
Blazor .NET 8 实现 StackOverflow 风格通知弹窗方案
核心实现步骤
- 移除模态遮罩与Modal结构:原代码中的
modal-backdrop是阻止页面点击的关键,直接删除;同时抛弃Bootstrap Modal的容器类,改用自定义定位容器实现悬浮弹窗。 - 固定弹窗定位:通过CSS将弹窗固定在页面右上角(匹配StackOverflow布局),确保不遮挡页面核心内容,且允许页面其他区域正常交互。
- 添加外部点击关闭逻辑:用透明全屏遮罩层监听弹窗外的点击操作,触发关闭事件,同时不影响页面内容可见性。
- 重构通知卡片结构:保留原通知内容,改用普通卡片样式模拟StackOverflow的视觉风格,优化交互细节。
修改后的代码实现
父组件(示例:MainLayout.razor)
@if (ShowNotificationPopup) { <!-- 透明遮罩:点击弹窗外部时关闭 --> <div class="notification-overlay" @onclick="ToggleNotificationPopup"></div> <!-- 弹窗容器 --> <div class="notification-popup-container"> <NotificationPopup OnClose="ToggleNotificationPopup" /> </div> } <!-- 通知触发按钮 --> <button class="notification-trigger" @onclick="ToggleNotificationPopup">🔔 通知</button> @code { private bool ShowNotificationPopup { get; set; } = false; private void ToggleNotificationPopup() { ShowNotificationPopup = !ShowNotificationPopup; } }
NotificationPopup.razor 组件
<div class="notification-card"> <div class="notification-header"> <h5>Notifications</h5> <button class="close-btn" @onclick="ClosePopup">×</button> </div> <div class="notification-body"> <p class="notification-item">有人点赞了你的回答</p> <p class="notification-item">你的问题收到新评论</p> <p class="notification-item">你关注的话题有新动态</p> </div> <div class="notification-footer"> <button @onclick="ClosePopup">关闭</button> </div> </div> @code { [Parameter] public EventCallback OnClose { get; set; } private async Task ClosePopup() { await OnClose.InvokeAsync(); } }
关键CSS样式
/* 全屏透明遮罩:仅用于监听外部点击,不遮挡内容 */ .notification-overlay { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; z-index: 999; background-color: rgba(0,0,0,0); } /* 弹窗容器:固定在右上角 */ .notification-popup-container { position: fixed; top: 60px; /* 适配导航栏高度调整 */ right: 20px; z-index: 1000; } /* 通知卡片样式 */ .notification-card { width: 350px; border: 1px solid #e1e4e8; border-radius: 8px; background-color: #fff; box-shadow: 0 4px 12px rgba(0,0,0,0.15); overflow: hidden; } .notification-header { padding: 12px 16px; border-bottom: 1px solid #e1e4e8; display: flex; justify-content: space-between; align-items: center; } .notification-header h5 { margin: 0; font-size: 16px; color: #24292e; } .close-btn { background: none; border: none; font-size: 20px; cursor: pointer; color: #6a737d; padding: 0; } .notification-body { padding: 16px; max-height: 400px; overflow-y: auto; } .notification-item { margin: 8px 0; padding: 8px; border-radius: 4px; cursor: pointer; color: #24292e; } .notification-item:hover { background-color: #f6f8fa; } .notification-footer { padding: 12px 16px; border-top: 1px solid #e1e4e8; text-align: right; } .notification-footer button { padding: 6px 12px; background-color: #0969da; color: #fff; border: none; border-radius: 6px; cursor: pointer; } .notification-footer button:hover { background-color: #0757a2; }
内容的提问来源于stack exchange,提问作者Benoît S
相关产品推荐
相关产品推荐

