我的 R Shiny 应用程序加载后,我想将焦点设置到 selectInput
元素,以便用户可以立即通过上下箭头选择一个项目并按回车键。
我试图捕获 JavaScript load
事件,将其发送到 R,然后使用 Shiny.addCustomMessageHandler
设置 selectInput
的焦点> 元素。
作为中间步骤,我还尝试使用 actionButton
中的点击事件来触发元素焦点。虽然我认为大部分部分应该在代码中,但 load
事件不会传输到服务器,焦点部分确实会被 JavaScript 获取。
此帖focusing the cursor in textArea after clicking an action button in shiny也没有帮助我到达终点线。
这是我目前所拥有的:
library(shiny)
ui <- fluidPage(
tags$head(tags$script('
window.addEventListener("load", function(){
alert("Loaded");
Shiny.setInputValue("loaded", 1) // new identical function to Shiny.onInputChange
});
')),
tags$head(tags$script('
Shiny.addCustomMessageHandler("focus", function(null) {
document.getElementById("select").focus()
});
')),
headerPanel("Focus", windowTitle = "Focus"),
fluidRow(
column(width = 2, class = "panel",
selectInput("select", label = "Your Choice", choices = c("Choice 1", "Choice 2"), selectize = TRUE),
actionButton("click", "Click")
),
column(width = 10,
textOutput("text")
)
)
)
server = function(input, output, session) {
observeEvent(input$loaded, {
session$sendCustomMessage("focus",list(NULL))
print("Loaded")
})
observeEvent(input$select, {
print("Selected")
})
observeEvent(input$click, {
session$sendCustomMessage("focus",list(NULL))
print("Clicked")
})
output$text <- renderText({
})
}
shinyApp(ui = ui, server = server)
感谢您的帮助。
最佳答案
打开控制台(使用 Chrome 时为 Ctrl+Shift+i),您将看到您的 JS 代码中存在一些错误。
主要是打开app时shiny
还没有准备好,所以找不到函数Shiny.setInputValue
。
要确保 shiny
准备就绪,请使用:
$(document).on("shiny:connected", function(){
......
});
现在,经过多次尝试,我发现要“聚焦”的元素并不是整个select
元素。它是它的 div
子元素,带有 selectize-input
类,您可以使用 $("#select ~ .selectize-control > .selectize-input") 选择
。
最后,要执行的好 Action 不是focus
,而是click
。这是完整的应用程序:
library(shiny)
js <- '
$(document).on("shiny:connected", function(){
alert("Loaded");
Shiny.setInputValue("loaded", 1);
Shiny.addCustomMessageHandler("focus", function(x){
$("#select ~ .selectize-control > .selectize-input").click();
});
});
'
ui <- fluidPage(
tags$head(tags$script(HTML(js))),
headerPanel("Focus", windowTitle = "Focus"),
fluidRow(
column(width = 2, class = "panel",
selectInput("select", label = "Your Choice",
choices = c("Choice 1", "Choice 2"), selectize = TRUE),
actionButton("click", "Click")
),
column(width = 10,
textOutput("text")
)
)
)
server = function(input, output, session) {
observeEvent(input$loaded, {
session$sendCustomMessage("focus", list(NULL))
print("Loaded")
})
observeEvent(input$select, {
print("Selected")
})
observeEvent(input$click, {
session$sendCustomMessage("focus", list(NULL))
print("Clicked")
})
output$text <- renderText({
})
}
shinyApp(ui = ui, server = server)
关于r - 将 Shiny 应用程序中的焦点设置为加载时的特定 UI 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61252694/