当我们想要在 Quarto HTML 文档中拥有两个不同的主题时,我们可以使用按钮在浅色和深色模式之间切换。标准按钮位于文档的右上角。我希望将此文档放在文档目录下方。这是一些可重现的代码:
---
title: "Change position theme button"
format:
html:
toc: true
theme:
light: default
dark: darkly
---
## Chapter
Some text to make it reproducible
### Test
输出:
可以看到主题切换按钮位于右上角。我想知道如何将它放在目录下方?
这比我预期的要稍微棘手一些,因为切换按钮是在页面加载后动态添加的。因此我们需要一些 JavaScript 来监视对 DOM 所做的更改,例如一个MutationObserver。
要做的第一件事是将
include-in-header: move-toggle.html
添加到您的 Quarto yaml 中。然后创建 move-toggle.html
,它会查找 DOM 中的更改,如果找到则移动按钮(并且目录也会加载):
<script>
document.addEventListener("DOMContentLoaded", function () {
const observer = new MutationObserver(function (mutations, obs) {
const toggleButton = document.querySelector('.quarto-color-scheme-toggle');
const toc = document.querySelector('#TOC');
// check if table-of-contents and button are loaded
if (toggleButton && toc) {
// move button (adjust as desired)
toc.after(toggleButton);
toggleButton.style.position = 'relative';
toggleButton.style.top = '0';
toggleButton.style.right = '0';
toggleButton.style.margin = '1em 0';
obs.disconnect(); // no need to keep observing
}
});
// observe the DOM for changes
observer.observe(document.body, { childList: true, subtree: true });
});
</script>
输出:
为了重现性,这里是完整的
qmd
文件。唯一的附加行是 include-in-header: move-toggle.html
。
---
title: "Change position theme button"
format:
html:
toc: true
theme:
light: default
dark: darkly
include-in-header: move-toggle.html
---
## Chapter
Some text to make it reproducible
### Test