ag-Grid - 在悬停行上显示按钮,就像在 Gmail 中一样

ag-Grid - show buttons on row hover like in Gmail

在 ag-Grid 中,我想在悬停行时显示操作按钮,就像在 Gmail 中一样。无论滚动位置如何,操作按钮都必须出现在网格的右端。

https://blog.ag-grid.com/build-email-client-with-ag-grid-like-gmail/ 中提到了一种方法。他们在最后一列使用了 cellRenderer 并在 "onCellMouseOver" 发生时在其中显示按钮。仅当最后一列(使用 cellRenderer)始终在视图中时,此方法才有效。如果该列不在视图中,操作按钮也会不在视图中。

我不能使用这种方法,因为在我的例子中,有很多列并且我的网格中的所有列不能同时显示在屏幕上。因此,根据滚动位置,右端可以有任何列,因此我们不知道要在哪一列上添加 cellRenderer。

我们将如何实现这一目标?

这是一个演示我的解决方案的插件:https://plnkr.co/edit/X4hCimLy6aL3j4eh

事实证明,这可以仅使用 CSS 来实现。这是我的做法:

  1. 添加一列用于显示操作按钮。使用 cellRenderer 在其中呈现按钮。把它钉在右边。
  2. 使用CSS,
    • 将 ag-pinned-right-cols-container 绝对定位到右侧
    • 通过将宽度设置为 0 来隐藏右页眉和间隔符
    • 对于未悬停的行,通过将其填充和宽度设置为 0 来隐藏其中的操作按钮单元格

这里是完整的CSS和解释:

/* Hide right header and spacer */
.ag-pinned-right-header,
.ag-horizontal-right-spacer {
  width: 0 !important;
  min-width: 0 !important;
}

/* Add absolute position so that action buttons column will appear on top of other columns. 
   pointer-events: none to pass on mouse events to behind columns */
.ag-pinned-right-cols-container {
  position: absolute !important;
  right: 0;
  pointer-events: none;
}
/* Reset pointer-events so that click can happen on action buttons */
.ag-pinned-right-cols-container * {
  pointer-events: initial;
}

/* Hide border of right-cols-container */
.ag-pinned-right-cols-container .ag-cell {
  border: none !important;
}

/* Show action buttons only for the row that is being hovered. 
   For rows which are not being hovered, hide them by setting their width and padding to 0. */
.ag-pinned-right-cols-container .ag-row:not(.ag-row-hover),
.ag-pinned-right-cols-container .ag-row:not(.ag-row-hover) .ag-cell {
  width: 0 !important;
  padding: 0 !important;
}

Ag-grid 的默认行悬停和行选择颜色具有一定的透明度。由于我们的操作按钮列绝对放置在其他列之上,因此由于这些透明颜色的混合方式,它的背景看起来更暗。

因此,在这种方法中最好使用不透明的背景色,如下所示:

.ag-theme-alpine {
  --ag-row-hover-color: hsl(207, 90%, 94%);
  --ag-selected-row-background-color: hsl(207, 87%, 86%);
}

总体而言,

优点:-

  1. 这是一个直接解决方案。您可以将代码放在 CSS 上方,您将获得悬停功能按钮。
  2. 这种方法与框架无关。我已经在 React 和 Angular 上测试过了。 (对于 Angular,您将不得不使用 ng-deep 来解决样式封装问题)

缺点:-

  1. 如果您已经将一列或多列固定在右侧,这将不起作用
  2. 未来版本的 ag-grid 可能会使用不同的 class 名称。所以这个 CSS 可能需要在升级 ag-grid
  3. 时更新