다크모드 적용하기

dev2820·2022년 3월 27일
0

그 외

목록 보기
5/6

html 버전

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        /*html의 color-mode 속성이 light이면 light모드 dark면 dark모드*/
        :root[color-mode="light"] {
            background:#efefef;
            color:#222222;
        }
        :root[color-mode="dark"] {
            background:#222222;
            color:#efefef;
        }
    </style>
</head>
<body>
    <button onclick="darkmodeToggle()">다크모드 토글</button>
    <p>다크모드</p>
    <script>
      const mode = window.localStorage.getItem('isDarkmode');
      if(!!mode) { // 저장된 다크모드 여부
        document.documentElement.setAttribute('color-mode',mode);
      }
      else { // 저장된 다크모드 여부가 없다면 OS가 쓰는 다크모드 가져오기
        if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
          document.documentElement.setAttribute('color-mode', 'dark');
        }
        else {
          document.documentElement.setAttribute('color-mode', 'light');
        }
      }
    </script>
</body>
</html>

vue3 composition api에 다크모드 적용하기

  setup() {
    const isDarkmodeRef = ref(document.documentElement.getAttribute('color-mode')==='dark');
    const darkmodeHandler = (isOn:boolean):void => {
      if(isOn) {
        isDarkmodeRef.value = true;
      }
      else {
        isDarkmodeRef.value = false;
      }
    }
    watch(isDarkmodeRef,(newVal)=>{
      document.documentElement.setAttribute('color-mode',newVal?'dark':'light');
      localStorage.setItem('isDarkmode', newVal?'dark':'light');
    });
    ...

ts입니다. 다 생략하고 setup만 봅시다. ref로 반응형 isDarkmodeRef 변수를 하나 만들고 handler 함수를 만들어준 다음, isDarkmodeRef에 watch를 적용해 color-mode 속성값을 바꿔줍니다. css등은 위의 html5 예제처럼 하면 됩니다.

읽어보니 너무 대충써서 조금 부연 설명 붙입니다.
document.documentElement.setAttribute,document.documentElement.getAttribute는 각각 아래처럼 html tag에 붙어있는 속성을 쓰고 읽는 코드입니다.

밑줄 친 부분처럼 html 태그에 color-mode 속성이 붙어 있다면 document.documentElement.getAttribute('color-mode') 로 읽어오는 식.
이게 dark이냐 light이냐에 따라서 css를 다르게 적용시켜주는 방식입니다.

:root[color-mode="light"] {
      background:#efefef;
      color:#222222;
}
:root[color-mode="dark"] {
      background:#222222;
      color:#efefef;
}

위의 css코드는 :root == <html> 이라고 보면 됩니다. html에 color-mode 속성값이 light냐 dark냐를 보는거죠.

window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches는 현재 OS가 어떤 모드를 지원하고 있는지 알려주는 코드입니다. 본인 컴퓨터 OS를 다크 모드로 해놨으면 prefers-color-schemedark로 되어 있을 겁니다.

profile
공부,번역하고 정리하는 곳

0개의 댓글