如何自定义通知提示框的显示位置?

志煜 阅读 18

我用的是 Ant Design 的 notification 组件,现在想让提示框出现在页面右侧中间的位置,而不是默认的右上角。试过改 placement 属性,但好像只支持四个角落,没有中间选项。

也尝试在全局样式里加了 .ant-notification 的 top 和 right 值,但这样会影响所有通知,而且计算起来很麻烦。有没有办法针对某一个通知单独设置位置?比如通过 style 或者 getContainer?

notification.open({
  message: '提示',
  description: '这是一条测试消息',
  placement: 'topRight', // 只能选这四个:topLeft/topRight/bottomLeft/bottomRight
});
我来解答 赞 10 收藏
二维码
手机扫码查看
1 条解答
设计师利君
Ant Design 的 notification 默认只支持四个角落的 placement,这个是写死在组件逻辑里的,确实没中间选项,想用 style 或 getContainer 撬动位置基本没戏——因为 getContainer 控制的是容器挂载点,不是单条通知的位置;style 只能改内部元素,notification 本身是固定定位在右上角的 div。

真要实现单条通知居中右侧显示,有两个靠谱方案:

第一个是直接自己写个轻量级 toast,用 fixed 定位 + 动画,几行代码就能搞定,比硬改 AntD 的.notification 容器省事多了:

const showToast = (message, description) => {
const container = document.body;
const el = document.createElement('div');
el.style.cssText =
position: fixed;
right: 24px;
top: 50%;
transform: translateY(-50%);
z-index: 9999;
background: #fff;
padding: 16px 24px;
border-radius: 4px;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
max-width: 384px;
animation: fadeIn 0.3s ease, slideIn 0.3s ease;
;
el.innerHTML =
<div style="font-weight: 500; margin-bottom: 8px;">${message}</div>
<div style="color: rgba(0,0,0,0.65);">${description}</div>
;
container.appendChild(el);
setTimeout(() => {
el.style.opacity = 0;
el.style.transform = 'translate(100px, -50%)';
setTimeout(() => el.remove(), 300);
}, 3000);
};


第二个方案还是用 AntD 的 notification,但把它的 container 挂到一个自定义的
上,然后这个容器自己用 fixed 定位在右侧中间:

// HTML 中先加个容器
// <div id="custom-toast-container" style="position: fixed; right: 24px; top: 50%; transform: translateY(-50%); z-index: 9999;"></div>

notification.config({
getContainer: () => document.getElementById('custom-toast-container'),
});


这样所有通知都集中在这个自定义容器里,自然就集中在右侧中间了——不过注意这是全局生效,如果你只想某一条居中、其他保持右上角,那就得动态创建/销毁这个容器,或者直接用第一个方案自写 toast,更灵活。

说白了,AntD 这个组件就是为角落通知设计的,真要偏离它的设计意图,不如自己写个简单的,还能避免样式冲突和定位计算的坑。
点赞
2026-02-26 01:03