웹사이트에 다크모드 만들기 PHP & Javascript
페이지 정보
최고관리자 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 작성일 21-05-27 09:21 2,609 0관련링크
본문
[code]
<?php $themeClass = ''; if (!empty($_COOKIE['theme'])) { if ($_COOKIE['theme'] == 'dark') { $themeClass = 'dark-theme'; } else if ($_COOKIE['theme'] == 'light') { $themeClass = 'light-theme'; } } ?>
[/code]
위 소스코드를 head.php 에 넣어주시고
[code]
<body class="<?php echo $themeClass; ?>">
[/code]
그누보드의 경우 테마의 head.php 나 head.sub.php 에 body 태그를 찾아서 class 에 넣어주세요.
직접 만든 사이트의경우 헤더를 담당하는 페이지에 넣어주세요.
원하는 다크모드 on off 하는 버튼 넣어주세요.
[code]
<script> const btn = document.querySelector(".btn-toggle"); const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)"); btn.addEventListener("click", function() { if (prefersDarkScheme.matches) { document.body.classList.toggle("light-mode"); var theme = document.body.classList.contains("light-mode") ? "light" : "dark"; } else { document.body.classList.toggle("dark-mode"); var theme = document.body.classList.contains("dark-mode") ? "dark" : "light"; } document.cookie = "theme=" + theme; }); </script>
[/code]
css 에서 light 나 dark 속성을 이용해서 만드시면 됩니다..
ex)
.light button { .... }
.light .calendar { ... }