이것은 긴 게시물이 될 것입니다. 귀하의 웹 사이트에서 적절한 다크 모드 구현에 대한 모든 리소스와 정보를 시도하고 동화 할 것입니다.
CSS Filter Hack!
이 설정은 이전 게시물에서 설명했습니다. 그리고 반복해야 합니다. 그것은 단지 해킹 일 뿐이며 적절한 완벽한 다크 테마 구현이 아닙니다.
JS 구현
이제 우리는 CSS를 사용하여 멋진 다크 모드를 만드는 방법을 알았습니다.
위에서 언급 한 구현의 경우 자바 스크립트 아이디어는 매우 간단합니다.
const html = document.getElementsByTagName('html')[0];
const toggleTheme = (theme) => {
html.dataset.theme = theme;
}
이제 UI에서 어두운 값(dark)과 밝은 값(light)을 사용하여 toggleTheme() 메서드를 호출하기 만하면 됩니다.
네이티브 다크(Dark) / 라이트(Light) 모드?
CSS 또는 js에서 밝음 / 어두움 모드에 대한 시스템 기본 설정을 감지 할 수 있다고 말씀 드리는 건가요?
물론입니다!
새롭고 멋진 미디어 쿼리를 만나보세요!
<script>
// If `prefers-color-scheme` is not supported, fall back to light mode.
// In this case, light.css will be downloaded with `highest` priority.
if (window.matchMedia('(prefers-color-scheme: dark)').media === 'not all') {
document.documentElement.style.display = 'none';
document.head.insertAdjacentHTML(
'beforeend',
'<link rel="stylesheet" href="/light.css" onload="document.documentElement.style.display = \'\'">'
);
}
</script>
<!--
Conditionally either load the light or the dark stylesheet. The matching file
will be downloaded with `highest`, the non-matching file with `lowest`
priority. If the browser doesn't support `prefers-color-scheme`, the media
query is unknown and the files are downloaded with `lowest` priority (but
above I already force `highest` priority for my default light experience).
-->
<link rel="stylesheet" href="/dark.css" media="(prefers-color-scheme: dark)">
<link rel="stylesheet" href="/light.css" media="(prefers-color-scheme: light)">
<!-- The main stylesheet -->
<link rel="stylesheet" href="/style.css">
위의 코드는 라이트 모드 / 어두운 모드에 대해 사용자가 설정 한 기본 설정을 확인합니다. 그리고 이 기본 설정에 따라 브라우저는 적절한 CSS 파일을 다운로드합니다.
한 가지 주목할 점은 시스템 환경 설정이 다크 모드이지만 브라우저는 다른 CSS도 다운로드 하지만 우선 순위가 가장 낮다는 것입니다.
자, 우리가 모든 것을 자바 스크립트로 하고 싶다면?
https://dev.to/akhilarjun/dark-mode-unmistified-1ji6
자바 스크립트 마법을 입력하세요!
자체 광고 경고 롤링 ??
이것은 우리가 논의했던 바닐라 js를 사용하여 구축 한 라이브러리입니다. 작업량을 단 두 줄로 줄입니다.
js 파일 포함
<script src="https://cdn.jsdelivr.net/gh/akhilarjun/tinylibs@latest/themejs/theme.min.js" onload="setupThemeIcon()"></script>
그리고 id theme-selector와 onclick 기능이 switchTheme (this)로 있는 이미지
<img src="./sun.svg"
data-light-src="./sun.svg"
data-dark-src="./moon.svg"
alt="light theme"
id="theme-selector"
onclick="switchTheme(this)">
data-light-src 및 data-dark-src (제공되는 경우)는 Html 태그의 테마 속성을 변경하는 동안 아이콘 사이를 전환하는 데 사용됩니다.
마이크 드롭 시간 ?
라이브러리는 시스템 환경 설정 변경을 자동으로 감지하고 테마를 어둡거나 밝게 전환합니다.
그리고 우리는 크롬 개발 도구를 사용하여 이것을 시도 할 것입니다.
참고 문헌
등록된 댓글이 없습니다.