【问题标题】:Download button in text Quarto文本四开本中的下载按钮
【发布时间】:2023-01-24 12:55:18
【问题描述】:
例如,我想在 pdf 或 csv 文档的句子中间有一个下载按钮。这意味着句子中应该有一个小按钮,提示您可以下载文档,而不是在导航栏或侧边栏中。这是一些可重现的代码:
---
title: "Download button in text Quarto"
format:
html:
code-fold: true
engine: knitr
---
I would like to have a download button [here]() for pdf or CSV document for example.
我不确定是否可以使用 downloadthis 包在一个句子中实现一个干净的按钮,因为它应该在一个句子的中间,周围有文字。
【问题讨论】:
标签:
button
text
download
quarto
【解决方案1】:
使用一点 CSS 和 javascript,可以很容易地完成。
---
title: "Download button in text Quarto"
format:
html:
code-fold: true
include-after-body: add_button.html
engine: knitr
---
```{r}
#| echo: false
library(downloadthis)
mtcars %>%
download_this(
output_name = "mtcars dataset",
output_extension = ".csv",
button_label = "Download data",
button_type = "default",
self_contained = TRUE,
has_icon = TRUE,
icon = "fa fa-save",
id = "mtcars-btn"
)
```
The following button is a download button for matcars data <span id="down-btn"></span> You can download the mtcars data as csv file by clicking on it.
添加按钮.html
<style>
#mtcars-btn {
font-size: xx-small;
padding: 0.2rem 0.3rem !important;
}
#down-btn {
margin-right: 2px;
margin-left: 2px;
}
a:has(#mtcars-btn) {
text-decoration: none !important;
}
</style>
<script>
function add_button() {
/* get the R generated button by its id */
let mtcars_btn = document.querySelector("a:has(#mtcars-btn)");
mtcars_btn.href = '#mtcars-btn';
/* get the placeholder where you want to put this button */
let down_btn = document.querySelector("span#down-btn");
/* append the R generated button to the placeholder*/
down_btn.appendChild(mtcars_btn)
}
window.onload = add_button();
</script>
解释
所以我在这里做了什么
-
首先,使用 downloadthis 和 id=mtcars-btn 创建了一个下载按钮,这样我们就可以使用这个 #mtcars-btn id 选择器通过 js 代码获取这个生成的按钮
-
然后使用 <span></span> 在段落文本中创建一个占位符,我希望下载按钮位于此处,并且在这种情况下,为 span 分配一个 id down-btn,这样我们就可以使用 @ 定位这个 span 987654333@。
-
然后使用 js,简单地将生成的下载按钮附加到占位符 span 标记,以便按钮位于我们想要的位置。
-
最后,使用一些 css 使这个按钮更小,减少按钮填充,创建一点左右边距并删除下划线。
就是这样!