【问题标题】:How to position google autocomplete predictions?如何定位谷歌自动完成预测?
【发布时间】:2021-08-23 01:33:45
【问题描述】:

我有一个表格,其中包含图片中的联系人列表。我还有一个事件会在单击一行时触发,因此它可以显示选定的联系人详细信息(我正在使用角度 NGIF 指令来显示和隐藏详细信息)

问题是因为我的谷歌输入被放置在一个 NGIF 块内,当用户展开联系人详细信息并尝试输入它时,预测(pac-container)显示在我单击的行上(在表格内)而不是在谷歌输入自动完成搜索框下方。

我试图操纵 pac-container 类的 css,但我找不到覆盖该类 css 的方法。

这是我的自动完成搜索框的 html

<div *ngIf="showGoogleAddress" class="mg-b-10" fxLayoutGap="10px" fxLayout="row" fxLayout.xs="column" fxLayout.sm="column" fxFlexFill>
          <div fxFlex>
            <mat-form-field appearance="outline" class="form-field">
              <mat-label>Google Address Search Box</mat-label>
              <input [debounceTime]="500" ngxAutocomPlace autocomplete="off" (selectedPlace)="placeChanged($event)" placeholder="ex: Phoenix, Arizona" matInput #googleAddress="matInput" >
              <mat-icon matSuffix>location_on</mat-icon>
              <mat-hint>Search for compolete address, or city</mat-hint>
            </mat-form-field>
          </div>

        </div>

还有,这里是展开细节后整个表单的截图

如果 google 自动完成框在 NGIF 之外,那么它会毫无问题地呈现预测。似乎因为我使用的是 NGIF 指令,所以 google 组件无法确定正确的位置(计算正确的位置)来呈现其预测..

当我尝试时

.pac-container {
  position: absolute !important;
  z-index: 100000;
}

没用。

【问题讨论】:

    标签: css angular google-maps-api-3


    【解决方案1】:

    我不得不使用 JS 进行 DOM 操作。所以我在 google 搜索框上添加了一个 (keyUp) 事件处理程序,其计算位置的方法如下:

    adjustResPosition() {
          setTimeout(() => {
            var gSearchBar = document.getElementById('googleBar');
            var topPos = (gSearchBar?.getBoundingClientRect().top || 0) + window.scrollY + 25;
            var leftPos = (gSearchBar?.getBoundingClientRect().left || 0) + window.scrollX;
    
            var gPreds = document.querySelector('.pac-container');
            gPreds?.setAttribute('style', `top: ${topPos}px; position: absolute!important; width: auto; left: ${leftPos}px`);
          }, 600);
        }
    

    我将 setTimeout 设置为 600 毫秒的原因是因为我有一个 500 毫秒的去抖动,直到它抓取下一个预测并将其放入 pac-container div 中

    注意,这不是最佳解决方案,可以使用ViewChildElementRef 进行改进

    【讨论】:

    • 嗨,我会尽快解决这个问题,并在 NgxAutocomPlace 指令的自述文件中添加一些自定义示例:) 随时在 github 页面上打开一个问题!
    猜你喜欢
    • 1970-01-01
    • 2017-10-16
    • 2015-01-01
    • 2012-02-20
    • 2016-01-31
    • 1970-01-01
    • 2014-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多