如何在Quarto文档中添加按钮实现双语切换?
实现Quarto文档双语切换按钮(仿主题切换样式)
完全可以实现这个功能,我们可以通过自定义HTML结构、CSS样式和JavaScript脚本,打造和主题切换按钮风格一致的双语切换控件,实现文本内容的语言切换。
下面是完整的可运行示例:
--- title: "双语切换示例" theme: light: flatly dark: darkly include-in-header: - text: | <style> /* 模仿主题切换按钮的样式 */ .lang-switch { position: fixed; top: 1rem; right: 5rem; background: var(--bs-body-bg); border: 1px solid var(--bs-border-color); border-radius: 0.375rem; padding: 0.25rem 0.5rem; cursor: pointer; font-size: 0.875rem; transition: all 0.2s ease; } .lang-switch:hover { background: var(--bs-secondary-bg); } /* 默认隐藏非英文内容 */ .zh-content { display: none; } /* 切换到中文时的显示状态 */ .show-zh .zh-content { display: block; } .show-zh .en-content { display: none; } </style> <script> document.addEventListener('DOMContentLoaded', function() { const switchBtn = document.getElementById('lang-switch-btn'); const body = document.body; // 初始化语言状态,优先读取本地存储 const savedLang = localStorage.getItem('quarto-lang') || 'en'; if (savedLang === 'zh') { body.classList.add('show-zh'); switchBtn.textContent = 'English'; } else { switchBtn.textContent = '中文'; } // 点击切换语言 switchBtn.addEventListener('click', function() { if (body.classList.contains('show-zh')) { body.classList.remove('show-zh'); switchBtn.textContent = '中文'; localStorage.setItem('quarto-lang', 'en'); } else { body.classList.add('show-zh'); switchBtn.textContent = 'English'; localStorage.setItem('quarto-lang', 'zh'); } }); }); </script> ---
示例内容
Example Section示例章节
This is just some example text which could be switched to a different language using a button like the one for themes.
这是一段示例文本,可以通过类似主题切换的按钮切换到不同语言。
print("Hello world!")
上面的代码会输出"Hello world!",你可以根据需要为代码添加对应的中文说明。
实现说明
- 样式匹配:通过CSS变量(
var(--bs-*))继承当前主题的颜色,确保按钮样式和主题切换按钮风格统一 - 状态记忆:使用
localStorage保存用户选择的语言,刷新页面后保持设置 - 内容结构:将不同语言的内容分别包裹在带
.en-content和.zh-content类的容器中,通过切换body类控制显示隐藏 - 灵活性:可以扩展到文档的任意部分,包括标题、段落、代码说明等
内容的提问来源于stack exchange,提问作者Quinten
相关产品推荐
相关产品推荐

