我正在构建一个闪亮的页面,我想让用户对图形元素进行一些控制 - 颜色,符号大小等。我正在放置一个下拉框,让用户控制图形中点的颜色。我希望颜色的名称本身以颜色显示。 ui.r
有:
selectInput("PColor","Choose a Color:",
choices=list(HTML('<p style="color: blue"> blue </p>'),
HTML('<p style="color: red"> red </p>'),selected="blue")
但是,不评估HTML代码。相反,下拉选项有'<p style="color: blue"> blue </p>'
,红色相似。无论如何我可以格式化这个列表中的每个选项吗?
由于
答案 0 :(得分:2)
以下解决方案适用于radioButtons()
:
radioButtons2 <- function(inputId, label, choices, selected){
temp.choices <- names(choices)
n <- length(choices)
names(temp.choices) <- paste0("ABCZYXWVU",1:n) -> temp.names
html <- as.character(radioButtons(inputId, label, temp.choices, selected=names(temp.choices[temp.choices==selected])))
for(i in 1:n){
html <- sub(paste0("<span>",temp.names[i],"</span>"), as.character(choices[[i]]), html)
}
attr(html,"html") <- TRUE
html
}
请注意,我已经改变了choices
中名称的作用;它的工作原理如下:
choices <- list(blue=HTML('<span style="color: blue"> blue </span>'), red=HTML('<span style="color:red"> red </span>'))
> cat(as.character(
+ radioButtons2("inputId","label",choices=choices, selected="blue")
+ ))
<div id="inputId" class="control-group shiny-input-radiogroup">
<label class="control-label" for="inputId">label</label>
<label class="radio">
<input type="radio" name="inputId" id="inputId1" value="blue" checked="checked"/>
<span style="color: blue"> blue </span>
</label>
<label class="radio">
<input type="radio" name="inputId" id="inputId2" value="red"/>
<span style="color:red"> red </span>
</label>
</div>
然而,selectInput()
的类似解决方案不起作用:html代码被忽略。您可以尝试使用selectInput2()
:
selectInput2 <- function(inputId, label, choices, selected = NULL, multiple = FALSE){
temp.choices <- names(choices)
n <- length(choices)
names(temp.choices) <- paste0("ABCZYXWVU",1:n) -> temp.names
html <- as.character(selectInput(inputId, label, temp.choices, selected=names(temp.choices[temp.choices==selected]), multiple))
for(i in 1:n){
html <- sub(temp.names[i], as.character(choices[[i]]), html)
}
attr(html,"html") <- TRUE
html
}
> cat(as.character(
+ selectInput2("inpuId", "label", choices, selected="blue")
+ ))
<label class="control-label" for="inpuId">label</label>
<select id="inpuId">
<option value="blue" selected="selected"><span style="color: blue"> blue </span></option>
<option value="red"><span style="color:red"> red </span></option>
</select>
此功能有效但html代码在应用程序中消失(如浏览器中的“Inspect element”所示)。如果您强制使用html代码,那么实际上html代码会出现在selectInput
的标签中。