빛인가 어둠인가? 웹사이트 접근성을 위한 원클릭 테마 전환
이제 웹사이트와 애플리케이션에는 일반적으로 낮에는 더 잘 보이는 밝은 테마와 밤에는 눈의 피로를 덜어주는 어두운 테마라는 두 가지 테마가 있습니다. 최고의 경험을 제공하려면 웹사이트에서 사용자가 선호도에 따라 이러한 테마 간에 쉽게 전환할 수 있도록 해야 합니다. 이 기사에서는 HTML, CSS 및 JavaScript를 사용하여 웹사이트에 어두운 모드 토글을 만드는 방법을 안내하여 사용자가 한 번의 클릭으로 밝은 테마와 어두운 테마 사이를 전환할 수 있도록 합니다.
이 튜토리얼에서는 밝은 모드와 어두운 모드를 나타내는 태양과 달 토글 버튼을 만들어 보겠습니다. 사용자가 버튼을 클릭하면 웹사이트가 이 두 모드 사이를 원활하게 전환합니다. 또한 향후 방문을 위해 사용자의 테마 기본 설정을 로컬 저장소에 저장할 것입니다.
데모를 확인하거나 이 GitHub 저장소에서 전체 소스 코드를 확인하세요. 이 단계별 가이드를 통해 대화형으로 학습하거나 아래로 스크롤하여 자세한 튜토리얼을 볼 수 있습니다.
전제 조건
시작하기 전에 다음 사항을 확인하세요.
- HTML, CSS, JavaScript에 대한 기본 지식
- 텍스트 편집기 또는 IDE(예: Visual Studio Code, Sublime Text)
- 테스트용 웹 브라우저
HTML 구조 설정
먼저 기본 HTML 구조를 만들고 토글 버튼과 페이지 콘텐츠를 구축하는 데 필요한 요소를 추가하겠습니다.
1. 새 HTML 파일을 만듭니다. 텍스트 편집기를 열고 DOCTYPE, HTML, head 및 body 태그를 포함한 기본 HTML 구조를 사용하여 새 index.html 파일을 만듭니다. 페이지에 제목 태그를 추가하고 외부 style.css 및 script.js 파일을 가져옵니다.
<meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Light/Dark Mode Toggle</title> <link rel="stylesheet" href="style.css"> <script src="script.js"></script>
2. body에 필요한 요소를 추가합니다. body 태그 안에 다음 요소를 추가합니다.
- 모든 콘텐츠를 감싸는 컨테이너 div
- 페이지의 h1 제목
- 간략한 설명을 위한 p단락
- 토글 스위치를 포함할 토글 컨테이너 div
- 해와 달 SVG 아이콘
<div class="container"> <h1 id="Light-Dark-Mode-Toggle">Light/Dark Mode Toggle</h1> <p>Click the toggle below to switch between dark and light modes.</p> <div class="toggle-container" id="themeToggle"> <svg class="sun-icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewbox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <circle cx="12" cy="12" r="5"></circle> <line x1="12" y1="1" x2="12" y2="3"></line> <line x1="12" y1="21" x2="12" y2="23"></line> <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line> <line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line> <line x1="1" y1="12" x2="3" y2="12"></line> <line x1="21" y1="12" x2="23" y2="12"></line> <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line> <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line> </svg> <svg class="moon-icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewbox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path> </svg> </div> </div> <script src="script.js"></script>
일반 index.html 파일은 다음과 같습니다.
밝은 모드와 어두운 모드에 대한 CSS 스타일 추가
이 섹션에서는 HTML 요소의 스타일을 지정하고 밝은 모드와 어두운 모드를 만듭니다. 또한 부드러운 색상 변경을 위해 전환을 사용하고 현재 모드에 따라 해와 달 아이콘의 가시성을 제어할 것입니다.
3. 밝은 색상과 어두운 색상에 대한 CSS 변수를 정의합니다. 텍스트 편집기에서 style.css 파일을 엽니다. :root 선택기를 사용하여 어두운 색상과 밝은 색상에 대한 CSS 변수를 정의합니다. 이를 통해 나중에 테마를 쉽게 사용자 정의할 수 있습니다. 어두운 색상이나 밝은 색상을 변경하고 싶다면 한곳에서 업데이트하면 됩니다.
/* Root selector for defining global CSS variables */ :root { --clr-dark: #333; /* Dark color for text in light mode, background in dark mode */ --clr-light: #fff; /* Light color for background in light mode, text in dark mode */ }
4. 기본 CSS 스타일을 설정합니다. 본문, .container 및 h1 요소에 스타일을 추가하여 페이지의 레이아웃과 서체를 설정합니다. 이러한 요소를 원하는 방식으로 맞춤 설정할 수 있습니다.
- body 색상에 대한 CSS 변수와 부드러운 색상 변경을 위한 전환을 사용하여 콘텐츠를 수직 및 수평으로 중앙에 배치합니다.
- .container 컨테이너 내의 콘텐츠를 중앙에 배치합니다.
- h1 제목 아래에 약간의 공간을 추가합니다.
/* Base styles for the body */ body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background-color: var(--clr-light); color: var(--clr-dark); transition: background-color 0.3s, color 0.3s; } /* Container for centering content */ .container { text-align: center; } /* Heading styles */ h1 { margin-bottom: 20px; }
5. 다크 모드를 위한 CSS 스타일을 추가합니다. 요소에 적용할 때 배경색과 텍스트 색상을 바꾸는 .dark-mode라는 CSS 클래스를 만듭니다.
/* Styles for dark mode */ .dark-mode { background-color: var(--clr-dark); color: var(--clr-light); }
6. 토글 아이콘의 스타일을 지정합니다. 해와 달 SVG 아이콘에 스타일을 추가하고 현재 모드에 따라 가시성을 제어합니다.
/* Styles for the toggle container */ .toggle-container { cursor: pointer; } /* Styles for the sun and moon icons */ .sun-icon, .moon-icon { width: 24px; height: 24px; transition: opacity 0.3s; } /* Hide moon icon by default (light mode) */ .moon-icon { display: none; } /* Show moon icon and hide sun icon in dark mode */ .dark-mode .sun-icon { display: none; } .dark-mode .moon-icon { display: inline-block; }
이러한 CSS 스타일을 사용하면 페이지에 기본 밝은 테마가 적용됩니다. 커서: 포인터 속성을 사용하면 토글을 클릭할 수 있음을 명확하게 알 수 있습니다.
JavaScript 기능 구현
이제 HTML 구조와 CSS 스타일이 준비되었으므로 JavaScript를 사용하여 어두운 모드 토글에 상호 작용을 추가하고 사용자 기본 설정을 기억하기 위한 로컬 저장소를 구현할 차례입니다.
7. DOM 요소를 선택합니다. script.js 파일을 열고 수정하려는 DOM 요소인 토글 버튼이 포함된 themeToggle ID를 선택합니다.
const themeToggle = document.getElementById('themeToggle'); const body = document.body;
8. Add event listeners to the toggle button. This is the core functionality of the dark mode toggle. Add an event listener to the themeToggle element to detect when the user clicks on it. It will add the dark-mode class to the body element if it’s absent, or removes the class if present.
themeToggle.addEventListener('click', () => { body.classList.toggle('dark-mode'); });
At this point, the toggle switch is functional, and clicking on it will switch between light and dark modes. However, if you reload the page while in dark mode, the website will revert to its default light mode.
9. Save user theme preferences in local storage. To save the user's theme preference even after the browser is closed, we'll use the localStorage object. Inside the event listener callback function, it checks if the body element has the dark-mode class.
- If it does, localStorage.setItem() saves the 'dark-mode' value to the 'theme' key.
- If it doesn't, localStorage.setItem() saves an empty string to the 'theme' key.
themeToggle.addEventListener('click', () => { body.classList.toggle('dark-mode'); // Store user preference in local storage if (body.classList.contains('dark-mode')) { localStorage.setItem('theme', 'dark-mode'); } else { localStorage.setItem('theme', ''); } });
10. Check for a saved theme preference. When the page loads, we want to check if there's a saved theme preference in the local storage. Use localStorage.getItem() to retrieve the value associated with the 'theme' key. If a 'dark-mode' preference exists in the local storage, apply the dark mode theme immediately by adding the dark-mode class to the body element.
Note: Make sure to place the getItem() method before the event listener to ensure it runs on page load.
// Check if user preference exists in local storage const currentTheme = localStorage.getItem('theme'); if (currentTheme) { body.classList.add(currentTheme); }
The Dark Mode Toggle in Action
We've implemented all the necessary components for our dark mode toggle, so let's see it in action. Try clicking the toggle switch to see the smooth transition between light and dark themes. Refresh the page to verify your theme preference is remembered.
Check out the complete source code on this GitHub repository.
Tips for Dark Mode Implementation
Creating a dark mode toggle is just the beginning. To create a user-friendly dark mode experience, there are several best practices to keep in mind.
Tip #1: Choose the Right Colors for Dark Mode
Selecting colors for dark mode involves more than simply inverting your light theme. The goal is to create a contrast between text and background colors for readability. Use tools like color contrast checkers to verify that your chosen colors meet WCAG (Web Content Accessibility Guidelines) standards. Remember, a well-designed dark mode should be easy on the eyes and work well across devices.
Tip #2: Create a User-Friendly Toggle Button
Create a clear visual distinction between light and dark modes to help users identify each mode easily. Your toggle switch or button should clearly show the current mode. You can implement effective approaches such as a sun and moon icon toggle, which is used in this article and is an easily recognizable choice, a light and dark mode text button, or a sliding switch with light/dark mode labels. Whichever design you choose, make sure it's consistent with your user interface and provides clear feedback when the user interacts with it.
Tip #3: Implement Smooth Transitions
To create a more polished user experience, use CSS transitions or animations for a seamless shift between light and dark modes. Make sure that all elements, including images and icons, smoothly transition to the new color scheme. This can be done by adjusting opacity, brightness, or swapping out images for dark mode-specific versions.
Conclusion
Adding a dark mode toggle to your website greatly improves user experience. This is not just about aesthetics but also usability and accessibility. It allows users to view content comfortably based on their preferences and lighting conditions.
Throughout this article, we've walked through the process of creating a simple dark mode toggle, covering HTML structure, CSS styling for light and dark themes, JavaScript functionality, and storing user preference. The key is to keep it simple and user-friendly. Don't forget to test your dark mode thoroughly to ensure all elements remain readable and functional.
Now it's your turn to create your own dark mode toggle! Share your CodePen or GitHub link in the comments below.
Further Reading
Check out these resources to learn more about dark mode implementation and advanced techniques:
- Dark theme - Material Design: Learn about dark mode implementation, anatomy, properties, and best practices from Material Design guidelines.
- Top 20 CSS Toggle Switches [2024] - LambdaTest: Explore various CSS toggle switch designs for your website.
위 내용은 HTML, CSS 및 JavaScript를 사용하여 다크 모드 토글을 만드는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

이것은 우리가 양식 접근성에 대해 한 작은 시리즈의 세 번째 게시물입니다. 두 번째 게시물을 놓친 경우 "사용자 초점 관리 : Focus-Visible"을 확인하십시오. ~ 안에

이 튜토리얼은 Smart Forms 프레임 워크를 사용하여 전문적인 JavaScript 양식을 작성하는 것을 보여줍니다 (참고 : 더 이상 사용할 수 없음). 프레임 워크 자체를 사용할 수 없지만 원칙과 기술은 다른 형태의 건축업자와 관련이 있습니다.

CSS Box-Shadow 및 개요 속성은 주제를 얻었습니다. 실제 테마에서 어떻게 작동하는지에 대한 몇 가지 예와 이러한 스타일을 WordPress 블록 및 요소에 적용 해야하는 옵션을 보자.

Svelte Transition API는 맞춤형 전환을 포함하여 문서를 입력하거나 떠날 때 구성 요소를 애니메이션하는 방법을 제공합니다.

이 기사는 Envato Market에서 사용할 수있는 최고의 PHP 양식 빌더 스크립트를 탐색하여 기능, 유연성 및 설계를 비교합니다. 특정 옵션으로 다이빙하기 전에 PHP 양식 빌더가 무엇인지, 왜 사용하는지 이해해 봅시다. PHP 양식

웹 사이트의 컨텐츠 프레젠테이션을 설계하는 데 얼마나 많은 시간을 소비합니까? 새 블로그 게시물을 작성하거나 새 페이지를 만들 때

NPM 명령은 서버 시작 또는 컴파일 코드와 같은 것들에 대한 일회성 또는 지속적으로 실행되는 프로세스로 다양한 작업을 실행합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)
