【问题标题】:Positioning cdk Overlay at mouse position将 cdk Overlay 定位在鼠标位置
【发布时间】:2020-04-17 14:08:12
【问题描述】:

我尝试将右上角的叠加层放置在鼠标位置。为了可视化它,我将向您展示它应该如何以及我得到了什么。

因此,要将右上角的叠加层定位在鼠标位置,必须从 event.clientX 值中减去叠加层的宽度(见下文)。但是总宽度必须是动态的,这取决于叠加层中内容的宽度。这可能会随着时间的推移而有所不同。那么如何获得叠加层宽度的确切值并在之后定位呢?

打开叠加层的按钮:

<button (click)="showTasks($event)"></button>

被调用的方法:

export class Component {
  constructor(private _tasksOverlay: OverlayService) {}

  showTasks(event) {
    this._tasksOverlay.open(OverlayComponent,event);
  }
}

覆盖服务:

@Injectable()
export class ServerTaskOverlayService {

  private _config = new OverlayConfig({});

  constructor(private overlay: Overlay) {}

  open(comp:ComponentType<any>,event:MouseEvent) {
    // Here the width of the overlay should already be known
    this._config.positionStrategy = this.overlay.position().global().left(event.clientX+"px").top(event.clientY+"px");

    const overlayRef = this.overlay.create(this._config);

    const filePreviewPortal = new ComponentPortal(comp);

    overlayRef.attach(filePreviewPortal);
  }
}

【问题讨论】:

    标签: angular-material overlay angular-cdk


    【解决方案1】:

    尝试使用 PositionStrategy 创建叠加层,然后更改 left 值。 例如:

    this.overlayRef = this.overlay.create({
      positionStrategy: this.positionStrategy
    });
    
    this.overlayRef.attach(new TemplatePortal(this.templateRef, this.viewContainerRef));
    
    this.positionStrategy.left(`${event.clientX - element width}px`);
    this.positionStrategy.apply();
    

    【讨论】:

      【解决方案2】:

      经过多次尝试,我意识到左下角是(0,0)轴点,y轴应该是负值(不知道为什么),所以对我有用的代码是:

      const positionStrategy = this.overlay.position().global().left(event.clientX+"px")
            .top((-1 * (window.innerHeight - event.clientY))+"px");
      
      this.overlayRef = this.overlay.create({
        positionStrategy
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多