웹사이트에 다크 모드를 구현하세요.
목차
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/MWbrNWeReference
이 문제에 관하여(웹사이트에 다크 모드를 구현하세요.), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/mattmarquise/implement-dark-mode-on-your-website-5c5a텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)