HTML, CSS 및 JavaScript를 사용하여 다크 모드 토글을 만드는 방법

WBOY
풀어 주다: 2024-08-29 15:00:26
원래의
453명이 탐색했습니다.

빛인가 어둠인가? 웹사이트 접근성을 위한 원클릭 테마 전환

이제 웹사이트와 애플리케이션에는 일반적으로 낮에는 더 잘 보이는 밝은 테마와 밤에는 눈의 피로를 덜어주는 어두운 테마라는 두 가지 테마가 있습니다. 최고의 경험을 제공하려면 웹사이트에서 사용자가 선호도에 따라 이러한 테마 간에 쉽게 전환할 수 있도록 해야 합니다. 이 기사에서는 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 파일을 가져옵니다.

<!DOCTYPE html>
<html lang="en">
<head>
    <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">
</head>
<body>
    <script src="script.js"></script>
</body>
</html>
로그인 후 복사

2. body에 필요한 요소를 추가합니다. body 태그 안에 다음 요소를 추가합니다.

  • 모든 콘텐츠를 감싸는 컨테이너 div
  • 페이지의 h1 제목
  • 간략한 설명을 위한 p단락
  • 토글 스위치를 포함할 토글 컨테이너 div
  • 해와 달 SVG 아이콘
<body>
    <div class="container">
        <h1>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>
</body>
로그인 후 복사

일반 index.html 파일은 다음과 같습니다.

How to Create a Dark Mode Toggle with HTML, CSS, and JavaScript

밝은 모드와 어두운 모드에 대한 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 스타일을 사용하면 페이지에 기본 밝은 테마가 적용됩니다. 커서: 포인터 속성을 사용하면 토글을 클릭할 수 있음을 명확하게 알 수 있습니다.

How to Create a Dark Mode Toggle with HTML, CSS, and JavaScript

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!