728x90
다크 모드
몇 번이나 테마를 겹치는 부분이라 '다크 모드'에 적합한 부분을 찾기가 쉽지 않네요. 이번에 한 작업은 웹 브라우저에 다크 모드 사용 시 블로그에 접속을 하면 바로 다크 모드로 접속되게 하는 부분입니다.
@media (prefers-color-scheme: dark) {
/* Your CSS */
}
저의 블로그는 html태그에 class로 테마가 변경됩니다. 그래서 이 부분을 어떻게 매치할까 고민하다가 위의 부분이 다크 모드라는 것을 몇 번이나 고민하고 찾고 해서 알게 되었네요. 바보같이...
html{
... light Theme
}
html.dark{
... dark Theme
}
아무튼 자바스크립트로 읽어 들이기만 해서 막상 해보면 몇 줄로만 가능한 부분인데 고민했습니다.
let $documentHtml = document.documentElement;
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
$documentHtml.classList.add("dark");
};
이제 여기서 'localStorage'까지 하면 됩니다. 밑의 소스는 darkTheme라는 key에 값이 참,거짓으로 판명합니다.
let
$storedTheme = localStorage.getItem("darkTheme"),
$documentHtml = document.documentElement;
if ($storedTheme !== null) {
if ($storedTheme === "true") {
$documentHtml.classList.add("dark");
}
} else if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
$documentHtml.classList.add("dark");
};
여기에 모바일까지 하면 좋겠어서 일단은 모바일을 검색합니다. 어느 사이트에는 '안드로이드'와 '아이폰'의 배경이 다르다고 해서 그것까지 검사합니다.
isMobile: function() {
return 'navigator' in window && window.navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)|(Android)|(PlayBook)|(BB10)|(BlackBerry)|(Opera Mini)|(IEMobile)|(webOS)|(MeeGo)/i);
},
isMobileInvoke: function() {
if(!module.isMobile) return;
for (let i = 0; i < $mobileMachine.length; i++){
if ($webAgent.indexOf($mobileMachine[i]) != -1) {
$mobile = true;
$mobileName = $mobileMachine[i];
break;
}
};
return $mobile == true ? document.body.setAttribute('is-mobile',$mobileName) : document.body.setAttribute('is-mobile',$mobile)
},
이번에는 body에 'is-mobile'라는 att.. 를 적고 모바일이 아니면 거짓, 모바일이면 모바일명을 적게 헸습니다.
이로서 하나의 css부분을 추가하면 됩니다.
html{
... light
}
html.dark{
... dark
}
body{
... back-Color /* #e5e6e6 */
}
html.dark body,
html.dark body[is-mobile="Android"]{
... Android back-Color /* #252627 */
}
html.dark body[is-mobile="iPod"],
html.dark body[is-mobile="iPad"],
html.dark body[is-mobile="iPhone"]{
... iphone back-Color /* #000000 */
}
마무리
앞으로 갈길이 멀지만 오늘 한 것 정리해 봅니다.
728x90