如何让PrimeNG SideBar仅在子div元素内部显示?
问题复现代码
<div style=" background-color: yellow; height: 350px; padding-top: 45%;"> <p-button type="button" (click)="visibleSidebar1 = true" icon="pi pi-arrow-right"> </p-button> <div style="background-color: green; height: 250px;"> <p-sidebar [(visible)]="visibleSidebar1" [baseZIndex]="10000"> <h1 style="font-weight:normal">Left Sidebar</h1> </p-sidebar> </div> </div>
现象:将
p-sidebar标签写在绿色背景子div内部,实际渲染时侧边栏超出子div范围,预期效果为侧边栏仅在绿色背景子div区域内部显示。
问题原因
PrimeNG Sidebar 组件默认会将DOM挂载到页面body节点下,且默认使用fixed定位相对视口计算位置,不受外层父容器的位置、裁剪规则约束,因此即使把组件标签写在子div内,渲染后也会超出容器范围。
实现步骤
- 给作为侧边栏容器的绿色div添加基础样式:设置
position: relative作为内部绝对定位元素的参照,添加overflow: hidden裁剪超出容器边界的内容 - 给容器添加Angular模板引用变量,用于指定Sidebar的挂载节点
- 给
p-sidebar组件配置appendTo属性,绑定到父容器引用,让组件DOM直接挂载到父容器内部而非body - 覆盖Sidebar默认的
fixed定位为absolute定位,让其相对父容器计算位置
修改后完整代码
<div style="background-color: yellow; height: 350px; padding-top: 45%;"> <p-button type="button" (click)="visibleSidebar1 = true" icon="pi pi-arrow-right"> </p-button> <!-- 侧边栏容器:添加相对定位、超出隐藏,添加模板引用 --> <div #sidebarWrap style="background-color: green; height: 250px; position: relative; overflow: hidden;"> <p-sidebar [(visible)]="visibleSidebar1" [baseZIndex]="10000" [appendTo]="sidebarWrap" [style]="{ position: 'absolute', top: 0, height: '100%' }"> <h1 style="font-weight:normal">Left Sidebar</h1> </p-sidebar> </div> </div>
补充说明:该配置下侧边栏的遮罩层也会挂载到父容器内,配合父容器的裁剪规则,所有侧边栏相关元素都会被限制在绿色区域内,符合预期效果。
内容的提问来源于stack exchange,提问作者janaka ravindra
相关产品推荐
相关产品推荐

