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

Bootstrap中div visibility:hidden失效 不修改display保留元素占位怎么解决

根因分析

你使用的*ngIf指令会在条件不满足时直接将整个col-sm-8元素从DOM树中移除,元素本身不存在,因此你给它添加的visibility属性、自定义类样式都无法生效,网格布局缺少8列的占位空间,右侧的col-sm-4元素自然会向左偏移。

解决方案

保留外层col-sm-8容器永久存在以占住网格位置,仅通过条件控制容器内部内容的可见性即可,同时可以添加pointer-events规则避免不可见状态下的按钮误触发。

调整后的CSS代码

.invisible-content {
    visibility: hidden;
    pointer-events: none;
}

调整后的HTML代码

<div class="row">
    <!-- 外层容器永久保留,仅动态切换内容可见性 -->
    <div class="col-sm-8" [ngClass]="{'invisible-content': !(loggedInUser && !loggedInUser.isPresident)}">
          <button pButton icon="pi" type="button" label="Create ABC Case" (click)="createABC()"></button>&nbsp;
          <button pButton icon="pi" type="button" label="Create XYZ Case"  (click)="createXYZ()"></button>
    </div>
    <div class="col-sm-4" *ngIf="loggedInUser && (loggedInUser.isPresident || loggedInUser.isVP)">
          <button pButton icon="pi" type="button" label="Print" (click)="test()"></button>
    </div>
</div>

如果你的业务场景要求条件不满足时完全不渲染内部按钮,也可以把内部按钮的*ngIf用ng-container包裹,外层容器依然永久存在,同样能实现占位效果:

<div class="row">
    <div class="col-sm-8">
        <ng-container *ngIf="loggedInUser && !loggedInUser.isPresident">
            <button pButton icon="pi" type="button" label="Create ABC Case" (click)="createABC()"></button>&nbsp;
            <button pButton icon="pi" type="button" label="Create XYZ Case"  (click)="createXYZ()"></button>
        </ng-container>
    </div>
    <div class="col-sm-4" *ngIf="loggedInUser && (loggedInUser.isPresident || loggedInUser.isVP)">
          <button pButton icon="pi" type="button" label="Print" (click)="test()"></button>
    </div>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 21:27:05