确实非常酷。不需要闪亮。
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(cell, cellData, rowData, rowIndex, cellIndex) {
然后你可以做例如if(rowIndex > 0)
跳过第一行,或者if(cellData.length > 100)
以包含超过 100 个字符的目标单元格。