웹사이트에 다크 모드를 구현하세요.

다크 모드는 기본 HTML, CSS 및 JS를 사용하여 웹사이트에 구현하는 매우 인기 있는 기능입니다. 그럼 아직 가지고 있지 않은 이유는 무엇입니까? 세 가지 간단한 단계를 통해 사이트를 개선하여 다크 모드를 통합할 수 있습니다! 시작하자.

목차



Step 1
Step 1
Step 3
Demo On CodePen

1 단계:

If you don't already have a website, simply create an HTML file.

<!-- index.html -->

<!DOCTYPE html>
  <head>
    <title>Dark Mode Feature</title>
    <meta charset="UTF-8">
    <meta http-equiv="Content-type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  </head>

  <body>
    ...
  <body>
</html>

Once you have that lets implement the HTML and CSS

2 단계:

In the basic HTML form lets now input everything we will need. Start by connecting your JS and CSS file. add

<!-- index.html -->

<!DOCTYPE html>
  <head>
    <title>Dark Mode Feature</title>
    <meta charset="UTF-8">
    <meta http-equiv="Content-type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!-- ADD CSS FILE -->
    <link rel="stylesheet" href="main.css">

    <!-- ADD JS FILE -->
    <script src="main.js"></script>
  </head>

  <body>
    ...
  <body>
</html>

Now we need to create those two files. Feel free to change the name of your css and

In the CSS file we'll add these lines of code.

/* main.css */
body {
  background-color: white;
  color: black;
}

.dark-mode {
  background-color: black;
  color: white;
}

Within the body we have specified that we want our default background to be white with black text. Then in the dark-mode class we've specified that we want want to change the background to black with white text.

Now we need to create the main.js file, the brain of our dark mode feature.

//main.js

function darkmode() {
  const wasDarkmode = localStorage.getItem('darkmode') === 'true';
  localStorage.setItem('darkmode', !wasDarkmode);
  const element = document.body;
  element.classList.toggle('dark-mode', !wasDarkmode);
}

function onload() {
  document.body.classList.toggle('dark-mode', localStorage.getItem('darkmode') === 'true');
}

Once you've successfully created both the main.css and main.js files there's one last thing.

3단계:

Though you may think you're done, you aren't. Ask yourself this very question. What if my website has multiple pages? how will each page stay in dark mode without returning to the default white background? The answer is far simpler than you think. In the initial body tag on each page add:

onload="onload()"

That's it. Hope this was helpful! Thanks for reading!

CodePen의 데모

https://codepen.io/mattmarquise/details/MWbrNWe

좋은 웹페이지 즐겨찾기