问题
In my Shiny app, the user mouses over some HTML output which consists of several spans, like this:
<div id="mydiv">
<span id="span1">foo</span>
<span id="span2">bar</span>
</div>
I want to get the ID of the span which the user is currently mousing over as a shiny input$... I know there are lots of js ways to do it, jquery get element where the cursor is, but I don't know how to integrate with Shiny, e.g. by using shinyjs https://deanattali.com/shinyjs/extend.
回答1:
Like this, if I correctly understand:
library(shiny)
js <- "
$(document).ready(function(){
$('span').on('mouseover', function(evt){
Shiny.setInputValue('span', evt.target.id);
});
})
"
ui <- basicPage(
tags$head(tags$script(HTML(js))),
tags$div(
tags$span(id = "span1", "foo"),
tags$span(id = "span2", "bar")
),
br(),
verbatimTextOutput("span")
)
server <- function(input, output){
output[["span"]] <- renderPrint({
input[["span"]]
})
}
shinyApp(ui, server)
来源:https://stackoverflow.com/questions/58541195/get-id-of-element-under-cursor-in-shiny