将 CSS 类添加到闪亮的 textOutput

seb*_*rno 7 css r css-selectors shiny

我需要在闪亮的应用程序中向一系列 textOutput 添加一个 CSS 类。

当我尝试时,例如:

textOutput('text', class = 'error')
Run Code Online (Sandbox Code Playgroud)

我得到:

Warning: Error in textOutput: unused argument (class = "error")
Run Code Online (Sandbox Code Playgroud)

可以更改该 textOutput 的 id 的 CSS。但是,我的 id 是动态生成的,所以这不是一个好的解决方案。一种可能的替代方法是“抓取”以/包含“error”(例如“error1”、“error2”)开头的所有 id,但我不确定这在我的 CSS 样式表中是否可行。

aeo*_*ail 9

一个简单的方法是使用闪亮的tagAppendAttributes功能。我通常发现将闪亮输出对象的 HTML 输出通过管道传输到其中更容易,如下所示:

library(shiny)
library(magrittr)

textOutput("foo") %>% 
  tagAppendAttributes(class = 'error')
Run Code Online (Sandbox Code Playgroud)

这会产生以下输出,其中包含错误类。

<div class="shiny-text-output error" id="foo"></div>
Run Code Online (Sandbox Code Playgroud)

你也可以用样式做同样的事情

textOutput("foo") %>% 
  tagAppendAttributes(style= 'color:green;')
Run Code Online (Sandbox Code Playgroud)
<div id="foo" class="shiny-text-output" style="color:green;"></div>
Run Code Online (Sandbox Code Playgroud)


dlu*_*kes 5

各种*Output函数返回带有您可以操作的属性的对象,class其中 - 只需使用以下函数检查它们结构str()

foo <- textOutput("foo")
print(foo)
# <div id="foo" class="shiny-text-output"></div>
str(foo)
# List of 3
#  $ name    : chr "div"
#  $ attribs :List of 2
#   ..$ id   : chr "foo"
#   ..$ class: chr "shiny-text-output"
#  $ children: list()
#  - attr(*, "class")= chr "shiny.tag"
Run Code Online (Sandbox Code Playgroud)

这意味着我们可以class通过textOutput函数覆盖该集合,如下所示:

foo$attribs$class <- "foo bar"
print(foo)
# <div id="foo" class="foo bar"></div>
Run Code Online (Sandbox Code Playgroud)

如果您想在添加新类的同时保留现有类,可以使用该paste()函数,并将其全部包装在自定义add_classes()函数中以方便使用:

add_classes <- function(el, classes) {
  el$attribs$class <- paste(el$attribs$class, classes)
  el
}

foo <- add_classes(foo, "baz qux")
print(foo)
# <div id="foo" class="foo bar baz qux"></div>
Run Code Online (Sandbox Code Playgroud)


seb*_*rno -1

答案是使用 CSS 选择器,例如:

[id^="error"] {
   ...
}
Run Code Online (Sandbox Code Playgroud)

它位于应用程序目录中的外部 css 文件中...通常命名为 style.css。