![](/img/trans.png)
[英]How can I add 'Read more' and 'Read less' functionality for long text in R Shiny?
[英]Read More Buttons for Long Text in R Shiny DT Datatables
我想在我的 R Shiny DT 數據表中包含“閱讀更多”和“閱讀更少”按鈕,用於溢出/長文本的單元格。
Devansh J 的精彩回答在純 CSS / javascript 數據表中演示了此功能。 您可以單擊“運行代碼片段”按鈕來查看它的運行情況。
不幸的是,我在 shiny 應用程序中無法獲得相同的結果。 我還查看了其他答案1和2 ,但它們並沒有讓我更接近 shiny 上下文中數據表的解決方案。 希望一輝能出面挽救局面!
這是一個可以從文本溢出按鈕中受益的 MWE。
library(shiny)
library(DT)
library(shinipsum)
text_df = data.frame(
numbers = 1:3,
letters = LETTERS[1:3],
text = c("Lorem", substr(shinipsum::lorem, 1, 100), substr(shinipsum::lorem, 1, 5000))
)
# Define UI for application that draws a histogram
ui <- fluidPage(
dataTableOutput("text_table")
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$text_table = renderDataTable({
datatable(text_df)
})
}
shinyApp(ui = ui, server = server)
確實很酷。 不需要 Shiny。
library(DT)
library(shinipsum)
text_df <- data.frame(
numbers = 1:3,
letters = LETTERS[1:3],
text = c(
"Lorem",
substr(shinipsum::lorem, 1, 100),
substr(shinipsum::lorem, 1, 5000)
)
)
js <- "
function(cell) {
var $cell = $(cell);
$cell.contents().wrapAll('<div class=\\\"content\\\"></div>');
var $content = $cell.find('.content');
$cell.append($('<button>Read more</button>'));
$btn = $cell.find('button');
$content.css({
height: '50px',
overflow: 'hidden'
});
$cell.data('isLess', true);
$btn.click(function () {
var isLess = $cell.data('isLess');
$content.css('height', isLess ? 'auto' : '50px');
$(this).text(isLess ? 'Read less' : 'Read more');
$cell.data('isLess', !isLess);
});
}
"
datatable(
text_df,
rownames = FALSE,
options = list(
"columnDefs" = list(
list(
"targets" = 2,
"createdCell" = JS(js)
)
)
)
)
您可以在 createdCell 中使用一個 function 和五個createdCell
:
function(cell, cellData, rowData, rowIndex, cellIndex) {
然后您可以執行例如if(rowIndex > 0)
跳過第一行,或者if(cellData.length > 100)
以超過 100 個字符的目標單元格。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.