You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R Shiny Sortable CSS如何为标签单独设置类使其拖拽后保持原有颜色

解决方案

核心逻辑是将样式从容器绑定改为标签自身绑定,避免拖拽到其他容器后样式失效,修改步骤如下:

  1. 调整CSS规则,为单独的标签类定义背景样式,不关联任何容器类
  2. 构造带自定义类的HTML标签元素,替换原有的纯文本标签,确保标签自带样式标识
    修改后完整可运行代码如下:
library(shiny)
library(sortable)

ui <- fluidPage(
  tags$style(HTML("
/* 直接给标签自身的类设置样式,与所在容器无关 */
.green-label {
  background-color: #53C1BE;
  width: 100%;
  display: block;
  /* 适配默认rank-list-item的内边距,让背景铺满整个选项 */
  margin: -3px -12px;
  padding: 3px 12px;
  border-radius: 3px;
  color: #fff;
}
.blue-label {
  background-color: #4080C9;
  width: 100%;
  display: block;
  margin: -3px -12px;
  padding: 3px 12px;
  border-radius: 3px;
  color: #fff;
}
")),
  fluidRow(
    column(6, uiOutput("example1")),
    column(6, uiOutput("example2"))
  )
)

server <- function(input, output, session) {
  
  output$example1 <- renderUI({
    bucket_list(
      header = NULL,
      group_name = "colours",
      orientation = "horizontal",
      class = "default-sortable",
      add_rank_list(
        text = " ",
        input_id = "green",
        # 传入带自定义类的标签元素,而非纯文本
        labels = tags$span(class = "green-label", "Green")
      )
    )
  })
  
  
  output$example2 <- renderUI({
    bucket_list(
      header = NULL,
      group_name = "colours",
      orientation = "horizontal",
      class = "default-sortable",
      add_rank_list(
        text = " ",
        input_id = "blue",
        labels = tags$span(class = "blue-label", "Blue")
      )
    )
  })
  
}

shinyApp(ui, server)

修改后拖拽标签到任意容器,标签都会保留自身的背景颜色。

内容的提问来源于stack exchange,提问作者Graham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 03:15:01