我目前正在使用 Rhandsontable,并且面临用户单元格选择的问题。当用户从最后一列(例如 C 列)中选择一个单元格,然后按右键盘箭头时,选择将循环回第一列(A 列)。我想防止这种行为,并使其类似于 Excel,一旦到达最后一列,您就无法继续前进。
这是我当前 Rhandsontable 的一个简单示例
library(rhandsontable)
df <- data.frame(A = 1:5, B = 6:10, C = 11:15)
rhandsontable(df)
在此示例中,如果用户从 C 列中选择一个单元格并按向右箭头键,则选择内容会跳回 A 列。我想防止这种循环行为。
这是向右箭头的操作方法。
library(rhandsontable)
library(htmlwidgets) # to use the onRender function
js <- c(
"function(el, x) {",
" var hot = this.hot;",
" const lastcol = hot.countCols() - 1;",
" Handsontable.hooks.add('beforeKeyDown', function(e) {",
" if(e.which == 39) {", # 39 is the key code for the right arrow
" e.stopImmediatePropagation();",
" e.preventDefault();",
" const selected = hot.getSelected();",
" if(selected !== void 0) {",
" const [row, column, row2, column2] = selected[0];",
" if(column != lastcol) {",
" hot.selectCell(row, column+1);",
" }",
" }",
" }",
" });",
"}"
)
df <- data.frame(A = 1:5, B = 6:10, C = 11:15)
rhandsontable(df) %>% onRender(js)
使用较新版本的 handsontable 库,我们可以使用以下 JavaScript 代码:
js <- c(
"function(el, x) {",
" var hot = this.hot;",
" const lastcol = hot.countCols() - 1;",
" const gridContext = hot.getShortcutManager().getContext('grid');",
" gridContext.removeShortcutsByKeys(['ArrowRight']);",
" gridContext.addShortcut({",
" group: 'navigation',",
" keys: [[ArrowRight]],",
" runOnlyIf: () => hot.getSelected() !== void 0,",
" callback: () => {",
" const selected = hot.getSelected();",
" const [row, column, row2, column2] = selected[0];",
" if(column != lastcol) {",
" hot.selectCell(row, column+1);",
" }",
" }",
" });",
"}"
)
但是 rhandsontable 没有维护并使用旧版本的 handsontable。