【问题标题】:How to change z-index of Angular CDK Drag and Drop?如何更改 Angular CDK 拖放的 z-index?
【发布时间】:2020-07-15 19:06:50
【问题描述】:

我在我的应用程序中使用Angular Material CDK Drag and Drop Functionality。拖放功能运行良好,除非我在对话框中使用它(对于大多数组件,我使用的是 Nebular,在本例中为 Nebular 对话框)。我遇到的问题是,只要我在对话框中拖动一个可拖动元素,该元素就会消失在对话框后面。放下后,它会重新出现在正确的位置。在屏幕截图中,我将“AAAA”元素从列表中拖出 - 它消失在对话框后面。

Stackblitz:https://stackblitz.com/edit/angular-znqckb

我正在使用以下实现:

 <div cdkDropList cdkDropListOrientation="horizontal" class="example-list" [cdkDropListData]="techs"
     (cdkDropListDropped)="drop($event)">
     <button *ngFor="let tech of techs" nbButton cdkDrag>{{tech}}</button>
 </div>

组件.ts:

drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(this.techs, event.previousIndex, event.currentIndex);
}

我没有修改样式表。我认为可以通过修改 z-index 以某种方式解决此问题,但我不知道如何将其应用于“拖动”元素。

【问题讨论】:

  • 你能做一个 Stackblitz 吗?
  • 我刚刚添加了 Stackblitz

标签: css angular angular-material drag-and-drop angular-cdk


【解决方案1】:

您可以更改 DragRefConfig,在您的组件中注入正确的配置(具有所需的 z-index)。例如:

const DragConfig = {
  dragStartThreshold: 0,
  pointerDirectionChangeThreshold: 5,
  zIndex: 10000
};

providers: [{ provide: CDK_DRAG_CONFIG, useValue: DragConfig }]

预览元素的 z-index 将为 10000 ;-)

欲了解更多信息:https://material.angular.io/cdk/drag-drop/api#DragRefConfig

【讨论】:

  • 这种方法适用于我接受的答案没有,可能是因为 CSS 特异性规则。这种方法需要@angular/cdk 9.2.4 或更高版本。该版本中添加了 zIndex 属性。
  • const 被放置在一个 module.ts 文件中,providers 语句被放置在该文件的@NgModule({}) 中。或者至少那是我必须做的。
  • 哦,伙计,你为我节省了很多时间。干杯:)
【解决方案2】:

我自己也在努力解决这个问题,我现在正在使用一种粗略的解决方法。在您的全局样式(styles.scss)中强制 .cdk-overlay-container 的 z-index 为 1000 应该可以得到您想要的结果。但这不是最佳做法。

在styles.scss中添加这个:

.cdk-overlay-container {
  z-index: 1000 !important;
}

Stackblitz here

据我所知,不可能在拖动预览(“拖动”元素)上强制使用 z-index,因为 cdk 将其 z-index 动态设置为内联样式。您正在使用的 Nebular 库似乎将叠加容器的 z-index 设置为 1040。Angular Material 库将拖动预览的 z-index 设置为 1000,这就是它位于叠加层后面的原因。 Vanilla Angular Material 将 cdk 叠加层的 z-index 设置为 1000,因此拖放将在该场景中起作用。

【讨论】:

    【解决方案3】:

    对于 9 之前的 Angular 材质版本。

    在html可拖动元素中:

    <div ... cdkDrag (cdkDragStarted)="onDragStarted($event)"</div>  
    

    在组件 ts 中:

    export class ...{
      zIndexSerial: number = 1000;
    
      onDragStarted(event: CdkDragEnd): void {
        event.source.element.nativeElement.style.zIndex=this.zIndexSerial+"";
        this.zIndexSerial = this.zIndexSerial+1;
      }
    

    【讨论】:

    • 不应该是CdkDragStart而不是...End吗?
    【解决方案4】:

    对于遇到相同问题的任何人。我发现解决方案是 z-index 仅适用于定位元素Refer to this link description here

    【讨论】:

    • 请添加您的答案,而不仅仅是一个链接
    【解决方案5】:

    对于 Angular 版本 8,我将以下内容添加到 styles.scss 并让它在模态中工作:

    .cdk-drag-preview {
        z-index: 9000 !important;
    }
    

    .cdk-drag-previewhttps://material.angular.io/cdk/drag-drop/overview#styling

    【讨论】:

      猜你喜欢
      • 2012-04-19
      • 2019-04-24
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      • 2019-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多