如何在reveal.js中设置两种代码高亮配色?
在reveal.js中实现两种代码高亮颜色
步骤1:引入两种highlight.js主题样式
在页面的<head>中,保留原有的深色高亮主题(比如示例中的monokai),同时新增一个浅色高亮主题(比如github、atom-one-light等,按需选择):
<link rel="stylesheet" href="../dist/reveal.css"> <link rel="stylesheet" href="../dist/theme/black.css" id="theme"> <!-- 深色高亮主题 --> <link rel="stylesheet" href="../plugin/highlight/monokai.css"> <!-- 浅色高亮主题 --> <link rel="stylesheet" href="../plugin/highlight/github.css">
步骤2:给目标代码块添加自定义类
给需要浅色高亮的代码块的<pre>标签添加自定义类,比如light-code:
<section> <pre data-id="code" class="light-code"><code> println("I want light color code here.") </code></pre> </section>
步骤3:添加自定义CSS覆盖样式
在<head>中插入<style>标签,编写CSS规则,让light-code类下的代码应用浅色主题的样式(以下以github主题为例,可根据你选择的浅色主题调整颜色值):
<style> /* 浅色代码块基础样式 */ .light-code { background: #ffffff !important; } .light-code code { color: #333333 !important; } /* 语法高亮颜色匹配 */ .light-code .hljs-keyword { color: #0000ff; } .light-code .hljs-string { color: #d14; } .light-code .hljs-comment { color: #998; font-style: italic; } .light-code .hljs-number { color: #099; } </style>
完整修改后的代码示例
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>reveal.js - Auto Animate</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link rel="stylesheet" href="../dist/reveal.css"> <link rel="stylesheet" href="../dist/theme/black.css" id="theme"> <!-- 深色高亮主题 --> <link rel="stylesheet" href="../plugin/highlight/monokai.css"> <!-- 浅色高亮主题 --> <link rel="stylesheet" href="../plugin/highlight/github.css"> <!-- 自定义切换样式 --> <style> .light-code { background: #ffffff !important; } .light-code code { color: #333333 !important; } .light-code .hljs-keyword { color: #0000ff; } .light-code .hljs-string { color: #d14; } .light-code .hljs-comment { color: #998; font-style: italic; } .light-code .hljs-number { color: #099; } </style> </head> <body> <div class="reveal"> <div class="slides"> <section> <pre data-id="code"><code> println("dark color code is fine here.") </code></pre> </section> <section> <pre data-id="code" class="light-code"><code> println("I want light color code here.") </code></pre> </section> </div> </div> <script src="../dist/reveal.js"></script> <script src="../plugin/highlight/highlight.js"></script> <script> Reveal.initialize({ center: true, hash: true, plugins: [ RevealHighlight ] }); </script> </body> </html>
补充说明
- 可在highlight.js的主题库中挑选更多浅色主题,替换示例中的
github.css即可。 - 若需要更精准的样式匹配,可打开引入的浅色主题CSS文件,复制对应选择器并加上
.light-code前缀,确保样式优先级生效。
内容的提问来源于stack exchange,提问作者Sadegh
相关产品推荐
相关产品推荐

