dark mode实现——全站暗黑模式切换

  水一篇文章,全站默认/暗黑模式切换的一种实现方式。

color

  暗黑模式下,给<html>设置一个class:dark-mode,切换到默认模式就删除该class。   写一个mixin:

@mixin dark-mode() { @at-root html.dark-mode &amp; { @content; } }

  使用方式如下:

h2 { color: black; svg { fill: black; } @include dark-mode { color: white; svg { fill: white; } } }

background

  在layout里加一个空的div,动画长宽分别是2倍的浏览器宽高*1.5,类似涟漪的效果。

&lt;template&gt; &lt;!-- ...... --&gt; &lt;div class=&quot;mode-bg&quot; :class=&quot;[themeMode, {active: !isFirst}]&quot; /&gt; &lt;!-- ...... --&gt; &lt;/template&gt; &lt;style lang=&quot;scss&quot;&gt; // ...... $circle-w: calc(200vw * 1.5); $circle-h: calc(200vh * 1.5); @keyframes light-dark { 0% { background: $background; width: 0; height: 0; } 100% { background: $background-dark; width: $circle-w; height: $circle-h; } } @keyframes dark-light { 0% { background: $background-dark; width: 0; height: 0; } 100% { background: $background; width: $circle-w; height: $circle-h; } } &gt;.mode-bg { position: fixed; z-index: $z-index-mode-bg; width: 0; height: 0; top: $header-height / 2; right: 50px; border-radius: 50%; &amp;.active { animation-duration: $animation-duration * 2; animation-timing-function: $animation-function; animation-fill-mode: forwards; transform: translate(50%, -50%); &amp;.light { animation-name: dark-light; } &amp;.dark { animation-name: light-dark; } } } // ...... &lt;/style&gt;
标签:前端
更新于: 2023-03-23 16:22:42 0