1

slickR有一个focusOnSelect选项 - 当单击轮播中的图像时,它会突出显示。如何访问选择事件以在 R Shiny 中使用以触发其他操作?具体来说,我想单击图像并让它更新带有图像名称的文本框。

要使用下面的示例,请将 3 张图片(image1.jpg、image2.jpg、image3.jpg)放在与应用程序相同的目录中。

library(shiny)

ui <- shiny::basicPage(

  slickROutput("my_slick",width='100%',height='200px')

)

server <- function(input, output) {

  output$my_slick <- renderSlickR({
      my_images <- c("image1.jpg", "image2.jpg", "image3.jpg")
      slickR(
        my_images,
        slideId = 'slick_images',
        width='90%'
      )
  })

}

shinyApp(ui, server)
4

1 回答 1

3

是你想要的吗?

library(shiny)
library(slickR)

my_images <- c("image1.png", "image2.png", "image3.png")

ui <- shiny::basicPage(

  slickROutput("my_slick",width='100%',height='200px'), 

  tags$p(id="textbox"),

  tags$script('var my_images = ["image1.png","image2.png","image3.png"];
              $("#my_slick").on("click", function(e){ 
                var slideClicked = $(this).find(".slick-active").attr("data-slick-index"); 
                document.getElementById("textbox").innerHTML = "Selected image: " + my_images[slideClicked];
              });')
)

server <- function(input, output) {

  output$my_slick <- renderSlickR({
    slickR(
      my_images,
      slideId = 'slick_images',
      width='90%'
    )
  })    
}

shinyApp(ui, server)

在此处输入图像描述

如果要在 Shiny 中获取所选图像的名称,请在脚本中添加一行:

  tags$script('var my_images = ["image1.png","image2.png","image3.png"];
              $("#my_slick").on("click", function(e){ 
                var slideClicked = $(this).find(".slick-active").attr("data-slick-index"); 
                Shiny.setInputValue("selectedImage", my_images[slideClicked]); 
                document.getElementById("textbox").innerHTML = "Selected image: " + my_images[slideClicked];
              });')

然后所选图像的名称在input$selectedImage.

编辑

以下是 OP 在评论中提出的改进脚本:

  tags$script('var my_images = ["image1.png","image2.png","image3.png"];
              var binary = true;
              $("#my_slick").on("click", function(e){ 
                if(e.target.localName == "img"){
                  if(binary){
                    var slideClicked = $(this).find(".slick-active").attr("data-slick-index"); 
                    Shiny.setInputValue("selectedImage", my_images[slideClicked]); 
                    document.getElementById("textbox").innerHTML = "Selected image: " + my_images[slideClicked];
                  }else{
                    document.getElementById("textbox").innerHTML = "";
                  }
                  binary = false;
                }else{
                  document.getElementById("textbox").innerHTML = "";
                  binary = true;
                }
              });')
于 2018-11-17T12:08:21.367 回答