Angular输入触发自动补全时如何实现背景模糊效果?
解决方案
问题根因
- 你直接给
mat-autocomplete设置了filter: blur(30px),会直接把自动完成面板自身模糊 - 原
.filter类的伪元素z-index设置过高,盖在了输入框和自动完成面板上方,导致输入框也被模糊 - Angular Material的自动完成面板默认渲染在全局的
cdk-overlay-container下,不是你写组件的DOM结构内,直接给mat-autocomplete加class不会作用到悬浮的面板上,需要用panelClass属性绑定样式
具体修改步骤
- 修改HTML代码
替换原HTML中自动完成相关的class绑定,调整后核心代码如下:
<div [class.page-blur]="input.value"> <div class="form-field d-flex align-items-center"> <div style="width: 3rem; height: 2rem" class="d-flex align-items-center justify-content-center" > <mat-icon>search</mat-icon> </div> <input #input type="text" class="input-search flex-grow-1 w-100" placeholder="Search for a food item ..." [formControl]="myControl" [matAutocomplete]="auto" (keyup)="onKeyUp($event)" /> <mat-autocomplete #auto="matAutocomplete" [panelClass]="input.value ? 'autocomplete-panel' : ''"> <mat-option *ngFor="let option of options" [value]="option.id"> {{ option.name.en }} </mat-option> <button class="view-btn mb-2" mat-button *ngIf="options.length > 2" (click)="onClickViewAllResults()">View all results</button> </mat-autocomplete> </div> </div>
- 修改CSS代码
- 删除原有
mat-autocomplete { filter: blur(30px); }规则 - 替换原
.filter类为新的.page-blur规则,调整层级逻辑,新增代码如下,其余原有CSS保留即可:
/* 页面背景模糊遮罩 */ .page-blur { position: relative; } .page-blur::before { content: ''; position: fixed; inset: 0; backdrop-filter: blur(8px); /* 可自行调整模糊数值到需要的效果 */ z-index: 999; pointer-events: none; /* 不影响输入框等元素的点击操作 */ } /* 输入框设置更高层级,避免被遮罩覆盖 */ .form-field { position: relative; z-index: 1000; } /* 自动完成面板设置更高层级,保证清晰显示在遮罩上方 */ .autocomplete-panel { z-index: 1001 !important; }
修改后当输入框有内容触发下拉面板展示时,只有遮罩下方的页面背景会被模糊,输入框和自动完成选项都可以清晰显示,和你需要的效果一致。
内容的提问来源于stack exchange,提问作者user16605035
相关产品推荐
相关产品推荐

