如何调整R Shiny中DataTables搜索栏的位置并自定义其外观
R Shiny DataTables搜索栏自定义实现方案
完全可以实现你要的效果,核心是通过DataTables的dom参数控制布局,再配合自定义CSS调整样式、添加搜索图标,完整可运行的示例代码如下:
library(shiny) library(DT) ui <- fluidPage( # 自定义CSS:控制搜索栏位置、样式,添加搜索图标 tags$style(HTML(" /* 搜索框容器居中 */ .dataTables_filter { float: none !important; text-align: center; margin-bottom: 20px; } /* 搜索框样式自定义 */ .dataTables_filter input { width: 300px !important; height: 38px; padding-left: 35px; border: 1px solid #ddd; border-radius: 20px; background-image: url('data:image/svg+xml;utf8,<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"%23666\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"11\" cy=\"11\" r=\"8\"></circle><line x1=\"21\" y1=\"21\" x2=\"16.65\" y2=\"16.65\"></line></svg>'); background-repeat: no-repeat; background-position: 12px center; background-size: 16px; } /* 去掉默认的搜索文字标签 */ .dataTables_filter label { font-size: 0; } ")), # DataTable输出 DTOutput("mytable") ) server <- function(input, output) { output$mytable <- renderDT({ datatable( iris, options = list( # dom参数控制布局:f代表搜索框,t代表表格,i代表信息,p代表分页 dom = "frtip" ) ) }) } shinyApp(ui, server)
关键配置说明
dom参数:我们调整了布局组件顺序,把代表搜索框的f放在最前面,保证搜索框出现在表格上方,默认的长度控制参数l如果有需要可以自行加回参数里- 自定义CSS规则:
- 覆盖默认的
.dataTables_filter浮动属性,设置text-align: center实现居中效果 - 搜索框用内嵌SVG作为搜索图标背景,不需要引入外部资源,适配性更强
- 隐藏了默认的「搜索:」文字标签,如果你需要保留可以删掉对应的CSS规则
- 覆盖默认的
- 所有样式都可以按需调整,比如修改搜索框宽度、圆角、边框颜色、图标颜色等参数即可
内容的提问来源于stack exchange,提问作者Hanuman95
相关产品推荐
相关产品推荐

