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

color

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

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

使用方式如下:

h2 {
  color: black;
  svg {
    fill: black;
  }

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

background

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

<template>
  <!-- ...... -->
  <div class="mode-bg" :class="[themeMode, {active: !isFirst}]" />  
  <!-- ...... -->
</template>
<style lang="scss">
  // ......
  $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;
    }
  }

  >.mode-bg {
    position: fixed;
    z-index: $z-index-mode-bg;
    width: 0;
    height: 0;
    top: $header-height / 2;
    right: 50px;
    border-radius: 50%;

    &.active {
      animation-duration: $animation-duration * 2;
      animation-timing-function: $animation-function;
      animation-fill-mode: forwards;
      transform: translate(50%, -50%);

      &.light {
        animation-name: dark-light;
      }

      &.dark {
        animation-name: light-dark;
      }
    }
  }
  // ......
</style>