我正在尝试向使用 RStudio 和 rmarkdown 生成的 html 文件添加一个按钮,该文件复制使用 kableExtra
生成的表到剪贴板。
作为演示,以下生成并显示一个表格:
library(dplyr)
library(kableExtra)
#making a dataframe into a table with kable
df<-data.frame(Flavor=c("Raspberry","Lemonade","Raspberry","Lemonade"),
Color=c("Blue","Pink","Red","Yellow"))
table_out<-df%>%
kable("html",align = 'clc')%>%
kable_styling(full_width = F,position="left",bootstrap_options = c("striped","bordered"))%>%
add_header_above(c("Colorful Stuff"=2))
table_out
我发现这段代码是从这里的答案中借来的:https://stackoverflow.com/a/42210996/9731173 ,允许我制作一个按钮:
<script type="text/javascript">
function selectElementContents(el) {
var body = document.body, range, sel;
if (document.createRange && window.getSelection) {
range = document.createRange();
sel = window.getSelection();
sel.removeAllRanges();
try {
range.selectNodeContents(el);
sel.addRange(range);
} catch (e) {
range.selectNode(el);
sel.addRange(range);
}
document.execCommand("copy");
} else if (body.createTextRange) {
range = body.createTextRange();
range.moveToElementText(el);
range.select();
range.execCommand("Copy");
}
}
<input type="button" value="Copy" onclick="selectElementContents(
document.getElementById('table_out') );">
上述问题(据我所知)是我指的不是我用 kableExtra
生成的表。正确。当我在渲染的 html 文件中单击复制按钮时,它不会复制 table_out
到剪贴板。我怎样才能给我的
kableExtra
表一个 ID 并正确引用它,以便我制作的“复制”按钮将表复制到剪贴板? 编辑:这是渲染文件的样子。我对外观很满意,但希望使复制按钮能够正常工作:
最佳答案
我通过将 id 属性添加到我的 kableExtra
来完成这项工作。表,然后在复制按钮中引用 id。
在这里查看 10.1.11:https://bookdown.org/yihui/rmarkdown-cookbook/kable.html ,
您可以使用 table.attr
添加属性。
你会看到我改变了kableExtra
要包括的部分 table.attr = "id=mytab"
,它允许在 R 代码块之外进行引用
我的全部功能代码是:
---
title: "Demo"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(dplyr)
library(kableExtra)
```
```{r}
#making a dataframe into a table with kable
df<-data.frame(Flavor=c("Raspberry","Lemonade","Rasp2berry","Lemonade"),
Color=c("Blue","Pink","Red","Yellow"))
table_out<-df%>%
kable("html",align = 'clc', table.attr = "id=mytab")%>%
kable_styling(full_width = F,position="left",bootstrap_options =
c("striped","bordered"))%>%
add_header_above(c("Colorful Stuff"=2))
table_out
```
<script type="text/javascript">
function selectElementContents(el) {
var body = document.body, range, sel;
if (document.createRange && window.getSelection) {
range = document.createRange();
sel = window.getSelection();
sel.removeAllRanges();
try {
range.selectNodeContents(el);
sel.addRange(range);
} catch (e) {
range.selectNode(el);
sel.addRange(range);
}
document.execCommand("copy");
} else if (body.createTextRange) {
range = body.createTextRange();
range.moveToElementText(el);
range.select();
range.execCommand("Copy");
}
}
<input type="button" value="Copy" onclick="selectElementContents( document.getElementById('mytab') );">
如果您有更好的解决方案或更强有力的解释,请仍然考虑发布答案。我的解决方案是蛮力的结果,而不是丰富的知识。
关于javascript - 如何在我的 Rmarkdown html 输出中获取复制按钮,以将 R 代码中生成的表格复制到剪贴板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67842801/