返回

Vuepress 深夜模式:更舒适的阅读体验

前端

随着各个系统都加入了「亮色/暗色模式」切换,Chrome 和 Edge 浏览器也支持了根据系统切换主题,作为互联网前沿的弄潮儿,我们也要追上潮流不是,所以通过这篇文章你可以学习到如何在自己的 Vuepress 博客里面使用暗色模式。

为什么需要暗色模式?

在昏暗的环境中,明亮的屏幕光线会对眼睛造成刺激,导致视觉疲劳和睡眠质量下降。暗色模式可以减少屏幕发出的蓝光,从而缓解眼睛疲劳,提高阅读舒适度,尤其是在夜间或光线较暗的环境中。

如何在 Vuepress 中添加暗色模式

1. 安装必要的依赖项

npm install vuepress-plugin-darkmode

2. 在 Vuepress 配置文件中启用暗色模式插件

在 Vuepress 配置文件中添加以下代码:

module.exports = {
  plugins: [
    ['vuepress-plugin-darkmode']
  ]
}

3. 配置暗色模式样式

在 Vuepress 主题的 styles/index.styl 文件中添加以下代码:

body {
  color: #212121;
  background-color: #ffffff;
  transition: background-color 0.3s ease-in-out, color 0.3s ease-in-out;
}

.dark-mode {
  color: #ffffff;
  background-color: #212121;
}

.code-wrapper {
  background-color: #333333;
}

.code-wrapper pre {
  color: #ffffff;
}

4. 添加暗色模式切换按钮

在 Vuepress 主题的 layout/Layout.vue 文件中添加以下代码:

<template>
  <div id="app">
    <header>
      <button @click="toggleDarkMode">切换暗色模式</button>
    </header>
    <main>
      <slot />
    </main>
    <footer>
      <p>Copyright © 2023</p>
    </footer>
  </div>
</template>

<script>
export default {
  methods: {
    toggleDarkMode() {
      document.body.classList.toggle('dark-mode')
    }
  }
}
</script>

结语

通过以上步骤,你就可以在 Vuepress 博客中添加暗色模式,为你的读者提供更舒适的阅读体验。如果你想了解更多关于 Vuepress 暗色模式的知识,可以参考官方文档:

Vuepress 暗色模式插件