拖动时如何更改光标?材质CDK拖放

时间:2018-12-07 17:43:18

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

使用Material CDK库中的拖放行为,我试图在拖动cdkDrag元素时更改光标。

例如,在this StackBlitz中,悬停时光标为grab。我希望在拖动时将其更改为grabbing。例如,在Google表格中抓行时会发生以下情况:

enter image description here

在阅读the documentation来设计拖放组件的样式时,向类添加光标属性似乎可以解决问题:

  

.cdk-drop-list-dragging:在用户拖动项目时添加到cdkDropList的类。

代码如下:

.example-box {
  /* other CSS properties */
  cursor: grab;
}

.cdk-drop-list-dragging {
  cursor: grabbing;
}

但是,正如您在StackBlitz中所看到的那样,这似乎并没有改变光标。我猜这是因为此类适用于列表,而不适用于光标。

另一种潜力是.cdk-drag-preview类:

  

.cdk-drag-preview:这是在用户拖动可排序列表中的项目时将在用户光标旁边呈现的元素。默认情况下,该元素看起来与被拖动的元素完全一样。

这似乎也不起作用。我认为是因为它更改了光标旁边呈现的元素,而不是光标本身。

关于如何在拖动时更改光标的任何想法?

4 个答案:

答案 0 :(得分:5)

以前的解决方案对我不起作用,但这里有一些很可能适用于仍有问题的人:

首先添加这个全局 CSS:

body.inheritCursors * {
  cursor: inherit !important;
}

并在您的 cdkDrag 元素中添加 cdkDragStarted 并将其附加到 .ts 文件中的方法:

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

在您的 .ts 文件中,您可以在拖动开始和停止时切换所需的光标:

bodyElement: HTMLElement = document.body;

  dragStart(event: CdkDragStart) {
    this.bodyElement.classList.add('inheritCursors');
    this.bodyElement.style.cursor = 'move'; 
    //replace 'move' with what ever type of cursor you want
  }

  drop(event: CdkDragDrop<string[]>) {
    this.bodyElement.classList.remove('inheritCursors');
    this.bodyElement.style.cursor = 'unset';
    ...
    ...
  }

这里有一个链接到一个有效的 example on StackBlitz

希望这对您有所帮助。

答案 1 :(得分:1)

只需将cursor: grabbing添加到您的example-box:active

.example-box:active {
  box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2),
              0 8px 10px 1px rgba(0, 0, 0, 0.14),
              0 3px 14px 2px rgba(0, 0, 0, 0.12);
  cursor: grabbing;
}

  

:active选择器用于选择和设置活动链接的样式。

     

单击链接后,该链接将变为活动状态。

     

提示::active选择器可用于所有元素,而不仅限于链接。

此处的其他信息

https://www.w3schools.com/cssref/sel_active.asp


Stackblitz

https://stackblitz.com/edit/angular-b8kjj3-r993mc?embed=1&file=app/cdk-drag-drop-overview-example.css

答案 2 :(得分:-1)

只需使用onmousedown = "changeCursorPoint()"事件函数-

private changeCursorPoint(): void {
    document.body.style.cursor = 'grabbing';
}

(cdkDropListDropped) = "clearCursorEvent()"上再次清除该功能

private changeCursorToDefault(): void {
    document.body.style.cursor = 'default';
 }

答案 3 :(得分:-1)

在链接的Stackblitz示例中,您没有使用下拉列表,因此希望CSS为:

.cdk-drag-dragging {
  cursor: grabbing;
}

在我的情况下,我使用表格主体元素上的列表进行拖放:

table tbody.cdk-drop-list-dragging td {
  cursor: grabbing !important;
}
相关问题