부트스트랩에서 밝고 어두운 테마 전환
17768 단어 css3bootstrapwebdevjavascript
부트스트랩의 테마
theming in Bootstrap은 내장된 SASS 변수를 통해 수행할 수 있지만 이 문서에서는 제공된 css 스타일시트를 사용할 것입니다.
Bootswatch에는 몇 가지 훌륭한 테마가 있습니다. 우리는 더 어두운 변형을 위해 Cyborg 테마를 사용할 것입니다. 그리고 빛의 경우 부트스트랩의 기본 테마를 사용할 것입니다.
자, 시작하겠습니다.
프로젝트 폴더 및 index.html 파일 생성
mkdir toggle-bootstrap-theme
cd toggle-bootstrap-theme
그 안에 index.html
파일을 생성합니다.
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<!-- Bootstrap CSS -->
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z"
crossorigin="anonymous"
/>
<!-- 🚨 Notice this link -->
<link id="dark-theme-style" rel="stylesheet" />
<title>Toggle Bootstrap Theme</title>
</head>
<body>
<nav class="navbar navbar-transparent">
<!-- 🚨 Notice the toggleTheme() function -->
<a
href="javascript:void()"
class="btn btn-outline-info btn-lg ml-auto font-weight-bold"
id="theme-toggler"
onclick="toggleTheme()"
></a>
</nav>
<div class="container-fluid">
<div class="jumbotron">
<h1 class="display-4">Hello, world!</h1>
<p class="lead">
This is a simple hero unit, a simple jumbotron-style component for
calling extra attention to featured content or information.
</p>
<hr class="my-4" />
<p>
It uses utility classes for typography and spacing to space content
out within the larger container.
</p>
<a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script
src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"
></script>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"
integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
crossorigin="anonymous"
></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
crossorigin="anonymous"
></script>
<!-- 🚨 Our custom JavaScript -->
<script src="index.js"></script>
</body>
</html>
위의 코드에서 다음 두 스니펫에 주목하십시오.
스타일시트를 동적으로 로드하는 <link>
<link id="dark-theme-style" rel="stylesheet" />
여기서는 JavaScript를 통해 어두운 테마 스타일시트를 렌더링합니다. 또한 우리는 이것을 기본 스타일시트 뒤에 보관했기 때문에 dark one에서 누락된 규칙이 있으면 기본값에서 가져옵니다.
<a> 테마 전환
<a
href="javascript:void()"
class="btn btn-outline-info btn-lg ml-auto font-weight-bold"
id="theme-toggler"
onclick="toggleTheme()"
></a>
이 앵커 태그는 사용자가 밝은 테마와 어두운 테마 사이를 전환하는 데 도움이 됩니다. JavaScript에서 함수toggleDark
를 생성할 것입니다. 보자.
index.js 파일 생성
// you can use app's unique identifier here
const LOCAL_STORAGE_KEY = "toggle-bootstrap-theme";
const LOCAL_META_DATA = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY));
// you can change this url as needed
const DARK_THEME_PATH = "https://bootswatch.com/4/cyborg/bootstrap.min.css";
const DARK_STYLE_LINK = document.getElementById("dark-theme-style");
const THEME_TOGGLER = document.getElementById("theme-toggler");
let isDark = LOCAL_META_DATA && LOCAL_META_DATA.isDark;
// check if user has already selected dark theme earlier
if (isDark) {
enableDarkTheme();
} else {
disableDarkTheme();
}
/**
* Apart from toggling themes, this will also store user's theme preference in local storage.
* So when user visits next time, we can load the same theme.
*
*/
function toggleTheme() {
isDark = !isDark;
if (isDark) {
enableDarkTheme();
} else {
disableDarkTheme();
}
const META = { isDark };
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(META));
}
function enableDarkTheme() {
DARK_STYLE_LINK.setAttribute("href", DARK_THEME_PATH);
THEME_TOGGLER.innerHTML = "🌙 Dark";
}
function disableDarkTheme() {
DARK_STYLE_LINK.setAttribute("href", "");
THEME_TOGGLER.innerHTML = "🌞 Light";
}
위의 코드는 자명하다고 생각합니다 😉 더 이상의 설명이 필요하지 않습니다.
산출
위의 코드를 모두 성공적으로 작성한 후 브라우저에서 간단히 열면index.html
출력을 볼 수 있습니다.
![](https://s1.md5.ltd/image/6caa68713d102a9ec61a3494c1afbad6.gif)
👉 The http call to dark stylesheet is done only once per session. If user switches back to light theme and then again dark theme, it is loaded from cache. See the Network panel in browser devtools to see this.
결론
몇 줄의 JavaScript 코드로 밝은 테마와 어두운 테마 사이를 얼마나 쉽게 전환할 수 있는지 배웠습니다.
sass, gulp, auto-refresh 등을 지원하는 완전한 Bootstrap 테마 생성 코드 기반을 찾고 있다면 내 github 저장소를 확인하십시오.
쉬다멘
/
부트스트랩 테마 키트
부트스트랩 테마를 빠르게 생성하고 선보입니다.
![](https://s1.md5.ltd/image/d41d8cd98f00b204e9800998ecf8427e.png)
부트스트랩 테마 키트
빠르게 ⚡ 생성 및 쇼케이스 🎯 부트스트랩 테마 🎨. Get Started 또는 See sample theme .
![](https://s1.md5.ltd/image/9958189c6e543b2492781097c47b635a)
![](https://s1.md5.ltd/image/e26103f08bfc9a4e779b6c771bfc9cde)
🚀 시작하기
☑️ 최소 요구 사항
node -v
// v10.17.0
git --version
// git version 2.x
⬇️ 따라야 할 단계
mkdir toggle-bootstrap-theme
cd toggle-bootstrap-theme
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<!-- Bootstrap CSS -->
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z"
crossorigin="anonymous"
/>
<!-- 🚨 Notice this link -->
<link id="dark-theme-style" rel="stylesheet" />
<title>Toggle Bootstrap Theme</title>
</head>
<body>
<nav class="navbar navbar-transparent">
<!-- 🚨 Notice the toggleTheme() function -->
<a
href="javascript:void()"
class="btn btn-outline-info btn-lg ml-auto font-weight-bold"
id="theme-toggler"
onclick="toggleTheme()"
></a>
</nav>
<div class="container-fluid">
<div class="jumbotron">
<h1 class="display-4">Hello, world!</h1>
<p class="lead">
This is a simple hero unit, a simple jumbotron-style component for
calling extra attention to featured content or information.
</p>
<hr class="my-4" />
<p>
It uses utility classes for typography and spacing to space content
out within the larger container.
</p>
<a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script
src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"
></script>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"
integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
crossorigin="anonymous"
></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
crossorigin="anonymous"
></script>
<!-- 🚨 Our custom JavaScript -->
<script src="index.js"></script>
</body>
</html>
<link id="dark-theme-style" rel="stylesheet" />
<a
href="javascript:void()"
class="btn btn-outline-info btn-lg ml-auto font-weight-bold"
id="theme-toggler"
onclick="toggleTheme()"
></a>
// you can use app's unique identifier here
const LOCAL_STORAGE_KEY = "toggle-bootstrap-theme";
const LOCAL_META_DATA = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY));
// you can change this url as needed
const DARK_THEME_PATH = "https://bootswatch.com/4/cyborg/bootstrap.min.css";
const DARK_STYLE_LINK = document.getElementById("dark-theme-style");
const THEME_TOGGLER = document.getElementById("theme-toggler");
let isDark = LOCAL_META_DATA && LOCAL_META_DATA.isDark;
// check if user has already selected dark theme earlier
if (isDark) {
enableDarkTheme();
} else {
disableDarkTheme();
}
/**
* Apart from toggling themes, this will also store user's theme preference in local storage.
* So when user visits next time, we can load the same theme.
*
*/
function toggleTheme() {
isDark = !isDark;
if (isDark) {
enableDarkTheme();
} else {
disableDarkTheme();
}
const META = { isDark };
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(META));
}
function enableDarkTheme() {
DARK_STYLE_LINK.setAttribute("href", DARK_THEME_PATH);
THEME_TOGGLER.innerHTML = "🌙 Dark";
}
function disableDarkTheme() {
DARK_STYLE_LINK.setAttribute("href", "");
THEME_TOGGLER.innerHTML = "🌞 Light";
}
👉 The http call to dark stylesheet is done only once per session. If user switches back to light theme and then again dark theme, it is loaded from cache. See the Network panel in browser devtools to see this.
빠르게 ⚡ 생성 및 쇼케이스 🎯 부트스트랩 테마 🎨. Get Started 또는 See sample theme .
🚀 시작하기
☑️ 최소 요구 사항
node -v // v10.17.0 git --version // git version 2.x
⬇️ 따라야 할 단계
git clone <forked-repo-url> cd bootstrap-theme-kit npm i npm run init npm start
🏆 기능
🌞 기본 및 🌙 어두운 테마
SCSS-7-in-1
전문가 팁: npx scss-7-in-1을 사용하여 어디서나 SCSS 7-in-1 아키텍처를 빠르게 생성
프로 팁:
npm run lint
를 사용하여 보풀을 만들고 npm run lint:fix
를 사용하여 고칠 수 있습니다.Commitzen Friendly
프로 팁: 파일을 준비한 후
npm run commit
를 사용하여 커밋 메시지를 커밋하기 쉽게 만드십시오. View on GitHub
그리고 네, 항상 자신을 믿으세요...
![](https://s1.md5.ltd/image/d27c3fa7b3f8faa3b06cd5d1f0a415b1.jpeg)
사진 제공: Nick Dunlap on Unsplash
Reference
이 문제에 관하여(부트스트랩에서 밝고 어두운 테마 전환), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/shhdharmen/toggle-light-and-dark-themes-in-bootstrap-4leo텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)