You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R Shiny DT:鼠标移出表格时如何让input[["cell"]]重置为NULL

R Shiny DT表格鼠标移出时重置input[["cell"]]为NULL的解决方法

问题说明

我正在开发R Shiny应用,需要实现鼠标悬停表格单元格时显示对应文本的功能。基于现有示例修改后遇到问题:当鼠标移出表格时,input[["cell"]]会保留最后触碰的单元格值,无法自动恢复为NULL。

原代码

library(shiny)
library(DT)

data(mpg, package = "ggplot2")

callback <- c(
  "table.on('mouseover', 'td', function(){",
  "  var index = table.cell(this).index();",
  "  Shiny.setInputValue('cell', index, {priority: 'event'});",
  "});"
)

ui <- fluidPage(
  br(),
  DTOutput("tbl"),
  htmlOutput("msg")
)

server <- function(input, output, session){

  dat <- mpg

  output[["tbl"]] <- renderDT({
    datatable(
      dat,
      callback = JS(callback)
    )
  })

  output[["tblfiltered"]] <- renderDT({
    datatable(
      filteredData(),
      fillContainer = TRUE,
      options = list(
        pageLength = 5
      )
    )
  })

  output$msg <- renderText(paste(input[["cell"]], collapse = ","))

}

shinyApp(ui, server)

解决方法

只需在JavaScript回调中添加表格的mouseleave事件监听,当鼠标离开整个表格时,将input[["cell"]]设为null即可。修改后的callback代码如下:

callback <- c(
  "table.on('mouseover', 'td', function(){",
  "  var index = table.cell(this).index();",
  "  Shiny.setInputValue('cell', index, {priority: 'event'});",
  "});",
  "table.on('mouseleave', function(){",
  "  Shiny.setInputValue('cell', null, {priority: 'event'});",
  "});"
)

完整修改后代码

library(shiny)
library(DT)

data(mpg, package = "ggplot2")

callback <- c(
  "table.on('mouseover', 'td', function(){",
  "  var index = table.cell(this).index();",
  "  Shiny.setInputValue('cell', index, {priority: 'event'});",
  "});",
  "table.on('mouseleave', function(){",
  "  Shiny.setInputValue('cell', null, {priority: 'event'});",
  "});"
)

ui <- fluidPage(
  br(),
  DTOutput("tbl"),
  htmlOutput("msg")
)

server <- function(input, output, session){

  dat <- mpg

  output[["tbl"]] <- renderDT({
    datatable(
      dat,
      callback = JS(callback)
    )
  })

  # 注:原代码中filteredData()未定义,若需使用需自行实现该函数,此处临时替换为dat避免报错
  output[["tblfiltered"]] <- renderDT({
    datatable(
      dat,
      fillContainer = TRUE,
      options = list(
        pageLength = 5
      )
    )
  })

  output$msg <- renderText({
    if(is.null(input[["cell"]])){
      "" # 鼠标移出时显示空文本
    } else {
      paste(input[["cell"]], collapse = ",")
    }
  })

}

shinyApp(ui, server)

说明

  • 添加的mouseleave事件会在鼠标离开表格区域时触发,将cell输入值重置为null
  • 优化了renderText部分,当input[["cell"]]为null时显示空文本,避免输出NULL字样

内容的提问来源于stack exchange,提问作者Duncan Ellis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 09:50:41