【发布时间】:2021-02-15 04:37:33
【问题描述】:
总结:我想在 R 中改编一个 JavaScript 库(即 OwlCarousel2),更准确地说是在 R Shiny 中。到目前为止,我已经做了几个步骤,但是我找不到在 HTML 结构的末尾(就在正文结尾之前)附加必要的 JS 脚本的方法。
OwlCarousel2 是一个允许创建卡片并使它们滑动的库。详情请见here。
到目前为止我做了什么:
-
首先,我检查了我是否可以仅使用 HTML、CSS 和 JS 重现该库的预期行为,遵循 this tutorial。
-
然后我尝试在 R Shiny 中进行调整。基本上,我创建了嵌入原始 HTML 的函数,我将 JS 和 CSS 放在
www中,然后我运行了应用程序以确保它可以正常工作。确实如此:显示卡片,并出现滑动行为。但这有点乱,所以我决定把它变成一个包,这样我(和其他人)可以更容易地重复使用它。 -
为了将它转换成一个包,我使用了两个来源:
我创建了三个函数:owl_carousel_item() 创建卡片,owl_carousel() 将卡片嵌入到 div 中,slider owl-carousel 类,html_dependency_owlcarousel() 包含依赖项。
html_dependency_owlcarousel <- function() {
htmltools::htmlDependency(
name = "owl.carousel",
version = "2.3.4",
package = "shinymisc",
src = "htmlwidgets/owl_carousel",
script = c("owl.carousel.min.js", "owl.carousel.js"),
stylesheet = c("owl.carousel.min.css", "style.css"),
all_files = FALSE
)
}
owl_carousel <- function(id, ...) {
tag <- htmltools::tags$div(
id = id,
class = "slider owl-carousel",
...
)
htmltools::tagList(
tag,
html_dependency_owlcarousel()
)
}
owl_carousel_item <- function(title, subtitle, content = NULL, button_text = NULL, width = "300px") {
if (!is.null(button_text))
button <- shiny::tags$div(class = "btn", value = button_text)
else
button <- NULL
shiny::tags$div(
class = "card",
style = paste0("width: ", width),
shiny::tags$div(class = "img"),
shiny::tags$div(
class = "content",
shiny::tags$div(class = "title", title),
shiny::tags$div(class = "sub-title", subtitle),
shiny::tags$p(content),
button
)
)
}
使用此代码(和依赖项),我生成了一个应用程序,其 HTML 结构几乎等同于我可以在包环境之外创建的应用程序:它显示卡片,但它们不会滑动。缺少的是<script>,它应该在这个结构的底部,就在<body> 的末尾之前。这就是卡片不会滑动的原因。
我尝试应用前面提到的书中this chapter 中描述的方法,但没有成功,因为我无法使htmlwidgets::createWidget() 与我的tag 一起工作。
因此,我的问题是:如何将以下脚本放在 HTML 结构的末尾?
$(".slider").owlCarousel({
loop: true,
autoplay: true,
autoplayTimeout: 2000, //2000ms = 2s;
autoplayHoverPause: true,
});
请记住,这些选项应该可以通过函数owl_carousel() 进行编辑(因此仅将其粘贴到owl_carousel() 中的tag 的末尾是不够的)。
我知道这一定不是很清楚,所以这里是 link to the repo 包含我目前所做的。
注意:这应该没有其他小部件那么难。这里没有 *Output 或 render* 函数,没有数据,只是一个嵌入盒子并让它们滑动的函数。
编辑:一些代码来测试它是否有效(它应该显示两张卡片和一个动画):
library(shiny)
library(fullPage)
ui <- fullPage(
menu = c("Section 1" = "section1"),
pageSection(
menu = "section1",
owl_carousel(
id = "test",
owl_carousel_item(
title = "test1",
subtitle = "subtitle1",
content = "this is a test"
),
owl_carousel_item(
title = "test2",
subtitle = "subtitle2",
content = "this is a test",
button_text = "button to click"
)
)
)
)
server <- function(input, output, session) {
}
shinyApp(ui, server)
【问题讨论】:
-
可能在标签列表中添加
htmltools::tags$script('ur jquery code here') -
谢谢,这适用于
shiny::fluidPage,但不适用于其他布局,例如fullPage::fullPage,因为该脚本在 HTML 结构中似乎“太高”了。此外,将 javascript 链接到包中的函数似乎不是一种干净的方法。 -
你能提供一个 MWE 以便我测试它吗?也感谢你让闪亮变得更好
-
也许如果你等待内容被加载会起作用
-
我已经知道如何在“经典”环境中进行这项工作。在这里,我的问题是由于它是一个 R 包,并且结构非常不同。因此,我无法生产 MWE。但是,您可以下载我在帖子中链接的存储库,以了解我所处的确切情况。
标签: javascript html r shiny