无法实现深色和浅色主题切换

问题描述 投票:0回答:1

我无法为我正在为课堂作业制作的网站制作深色和浅色主题。

我的想法基本上是这样的,作为我在我使用的网站上发现的一个例子,我希望所有页面中都存在“btn”,一旦我交换主题,它就会改变所有页面:

Dark and light theme switch

但是我做不到。

这就是我目前的代码,我真的不知道代码共享是这样,所以如果我最终犯了错误,我深表歉意。

我的索引 HTML 页面代码:

<!DOCTYPE html>
<html lang="en">
    <!-- para lingua português é só colocar um pt -->
    <head>
        <meta charset="utf-8"/>
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">
        <link rel="stylesheet" href="../CSS/Costumisation_Index.css">
        <link rel="icon" type="image/png" href="../Images/LogoIcon.png">
        <title>HOME</title>
    </head>
    <body class="d-flex flex-column min-vh-100">
        <header>
            <nav class="navbar navbar-expand-lg">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#"><img src="../Images/LogoNavBar.png"></a>
                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    <div class="collapse navbar-collapse" id="navbarNav">
                        <ul class="navbar-nav mx-auto">
                            <li class="nav-item">
                                <a class="nav-link" href="Index.html">HOME</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="About.html">ABOUT</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="Hobbies.html">HOBBIES</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="Software.html">SOFTWARE</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="Portfolio.html">PORTFOLIO</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="Contacts.html">CONTACTS</a>
                            </li>
                        </ul>
                    </div>
                    <div class="theme-buttons position-absolute end-0">
                        <button type="button" class="btn btn-light">Light Theme</button>
                        <button type="button" class="btn btn-dark">Dark Theme</button>
                    </div>
                </div>
            </nav>
        </header>
        <div class="d-flex flex-grow-1">
            <div class="split left">
                <div class="centered">
                    <h1>BEM VINDOS</h1>
                    <h3>Ao meu site pessoal</h3>
                    <p>
                        O meu nome é Anibal Artur Pinto Martins Batista da Silva, mas como é muito grande e o meu pai tem um nome parecido ao meu
                        eu simplesmente me introduzo por Anibal Artur Silva.
                    </p>
                    <p>Tenho 30 anos, sou natural da Africa do sul e resido em portugal desde os 4 anos de idade.</p>
                    <p>
                        Desde pequeno que tenho fascinio pela area da multimedia especificamente pela area do Cinema, TV , Imagem e Animação, mas como tenho 0% de talento para o desenho tive
                        que deixar o sonho da animação para traz e focar nas outras duas que é basicamente a area de Imagem e Video.
                    </p>
                    <p>Para saberem mais sobre mim é só seguir as instruções</p>
                    <p><i class="bi bi-arrow-bar-down"></i></p>
                    <a href="About.html" class="btn btn-outline-light botao-pagina">Descobre mais Sobre Mim<i class="bi bi-arrow-right-short"></i></a>
                </div>
            </div>
            <div class="split right">
                <div class="centered">
                    <img src="../Images/LogoHome.png" alt="ASilva Personal Logo">
                </div>
            </div>
        </div>
        <footer class="mt-auto text-center text-white">
            <!-- Grid container -->
            <div class="container p-4 pb-0">
            <!-- Section: Social media -->
                <section class="mb-4">
                    <!-- Facebook -->
                    <a class="btn btn-outline-light btn-floating m-1 btn-facebook footer-btn" href="#" role="button"><i class="bi bi-facebook"></i></a>

                    <!-- Twitter -->
                    <a class="btn btn-outline-light btn-floating m-1 btn-twitter footer-btn" href="#" role="button"><i class="bi bi-twitter"></i></a>

                    <!-- Discord -->
                    <a class="btn btn-outline-light btn-floating m-1 btn-discord footer-btn" href="#" role="button"><i class="bi bi-discord"></i></a>

                    <!-- Github -->
                    <a class="btn btn-outline-light btn-floating m-1 btn-github footer-btn" href="#" role="button"><i class="bi bi-github"></i></a>
                </section>
            <!-- Section: Social media -->
            </div>
            <!-- Grid container -->

            <!-- Copyright -->
            <div class="text-center p-3 footer-copyright">
            © 2023 Copyright:
            <a class="footer-link" href="#">ASilvaVisualPath.com</a>
            </div>
        <!-- Copyright -->
        </footer>
        <script defer src="JavaScript/LightDarkTheme.js"></script>
        <!-- jQuery -->
        <script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="sha256-/C2I/9qILMxbZZ0Xr+flJup6UKg2QQ4xMmR02Cq5OfY=" crossorigin="anonymous"></script>
        <!-- Popper.js -->
        <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script>
        <!-- Bootstrap JavaScript -->
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.3.2/js/bootstrap.min.js" integrity="sha512-WW8/jxkELe2CAiE4LvQfwm1rajOS8PHasCCx+knHG0gBHt8EXxS6T6tJRTGuDQVnluuAvMxWF4j8SNFDKceLFg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    </body>
</html>

我的索引 CSS 页面:

body {
    margin: 0; /* Remove default margin*/
    padding: 0;
    transition: background-color 0.5s ease;
    font-family: Arial, sans-serif;
}

/* Palete de cores*/

/* Light Mode Styles */
body.light-mode {
    background-color: #0080FF;
    color: #1B1B1B;
}

/* Dark Mode Styles */
body.dark-mode {
    background-color: #00437B;
    color: #EDEDED;
}

/* Theme Buttons Styles */

/* Adjust the position of the theme buttons on smaller screens */
@media (max-width: 768px) {
    .theme-buttons {
        position: static;
        margin-top: 120px;
        margin-right: 50px;
    }
}

/* Adjust the position of theme buttons on larger screens */
@media (min-width: 769px) {
    .position-relative {
        position: relative;
    }
    .position-absolute {
        position: absolute;
        top: 0;
        right: 0;
        margin-top: 150px; /* Adjust the top margin as needed */
        margin-right: 150px;
    }
}

/* Barra de navegação */
.navbar{
    padding: 0;
}

.active{
    color: #ffffff;
}

.nav-link{
    position: relative;
}

.nav-link::after{
    content: '';
    opacity: 0;
    transition: all 0.5s;
    height: 2px;
    width: 100%;
    background-color: #295773;
    position: absolute;
    bottom: 0;
    left: 0;
}

.nav-link:hover::after{
    opacity: 1;
}

.navbar .navbar-nav {
  margin-top: 1em;
  margin-bottom: 1em;
  border-top: 2px solid #000;
  border-top-color: white;
  border-bottom: 2px solid #000;
  border-bottom-color: white;
}

.navbar .nav-item{
    margin-left: 25px;
    padding: 0.5em 1em;
}

.navbar .container-fluid {
    flex-direction: column;
    background-color: #000033;
    z-index: 1; /* Ensure the navbar is above other elements */
}

.navbar-brand img {
    margin-top: 20px;
    max-height: 100px; /* Adjust the maximum height as needed */
}

.navbar-brand, .navbar-nav .nav-link {
    color: #3FA9F5; /* Text color for the navbar brand and links */
    font-size: 1.1em;
}

.navbar .navbar-nav .nav-link:hover{
    color: #295773;
}

.navbar-toggler {
    border-color: #fff; /* Border color for the navbar toggle button */
}

/* Divide o ecrã a metade */
.split {
    height: 100vh;
    width: 50%;
    display: flex;
    flex-direction: column; /* Define layout para coluna */
    justify-content: flex-start; /* Alinhar conteudo ao inicio (topo)*/
    align-items: center;
    overflow-x: hidden;
    padding-top: 100px;
}

/*Controlo do lado esquerdo*/
.left {
    padding-left:150px;
    left: 0;
}
    .left h1{
        font-size: 50px;
    }
    .left h3{
        font-size: 25px;
    }
    .left p{
        margin-bottom: 15px; /* Adjust the margin-bottom as needed*/
    }

/*Controlo do lado direito*/
.right {
    right: 0;
}

/*Para centralizar o conteudo verticalmente e horizontalmente*/
.centered {
    text-align: center;
}
    /*Dar estilo ou formatar a imagem dentro do contentor, se necessario*/
    .centered img {
        width: 500px;
        border-radius: 50%;
    }

/* Footer styles */
footer {
    background-color: #000033;
    position: relative; /* Important for stacking order */
    
}

.footer-copyright, .footer-link {
    color: #295773; /* Change this to the text color you want in the copyright section */
    background-color: rgba(0, 0, 0, 0.2);
}
/* Facebook icon color */
.btn-facebook {
    color: #3b5998; /* Facebook blue color */
}

/* Twitter icon color */
.btn-twitter {
    color: #1da1f2; /* Twitter blue color */
}

/* Discord icon color */
.btn-discord {
    color: #7289da; /* Discord color */
}

/* Github icon color */
.btn-github {
    color: #4078c0; /* Github color */
}

/* Button outline color */
.footer-btn {
    border-color: #295773; /* Change this to the color you want */
}

/* Button hover effect */
.footer-btn:hover {
    background-color: #295773; /* Change this to the background color you want on hover */
    color: #3FA9F5; /* Change this to the text color you want on hover */
    border-color: #295773; /* Change this to the border color you want on hover */
}

我的 JavaScript 代码:

// script.js

// document.addEventListener('DOMContentLoaded', function () {
//     setDefaultTheme();

//     // Add event listeners to theme buttons
//     document.querySelector('.btn-light').addEventListener('click', () => {
//         document.body.classList.remove('dark-mode');
//         document.body.classList.add('light-mode');
//         localStorage.setItem('preferred-theme', 'light-mode');
//     });

//     document.querySelector('.btn-dark').addEventListener('click', () => {
//         document.body.classList.remove('light-mode');
//         document.body.classList.add('dark-mode');
//         localStorage.setItem('preferred-theme', 'dark-mode');
//     });
// });



// LightDarkTheme.js

document.addEventListener('DOMContentLoaded', function () {
    // Check if a theme preference is stored
    const preferredTheme = localStorage.getItem('preferred-theme');

    // If a preference is stored, apply it
    if (preferredTheme) {
        document.body.classList.add(preferredTheme);
        toggleThemeButtons();
    } else {
        // If no preference is stored, set the default theme and show only the dark theme button
        setDefaultTheme();
        hideLightThemeButton();
    }

    // Add event listener to the dark theme button
    document.querySelector('.btn-dark').addEventListener('click', () => {
        // Toggle between light and dark themes
        document.body.classList.toggle('light-mode');
        document.body.classList.toggle('dark-mode');

        // Toggle the visibility of theme buttons
        toggleThemeButtons();
    });

    // Add event listener to the light theme button
    document.querySelector('.btn-light').addEventListener('click', () => {
        // Toggle between light and dark themes
        document.body.classList.toggle('light-mode');
        document.body.classList.toggle('dark-mode');

        // Toggle the visibility of theme buttons
        toggleThemeButtons();
    });

    function setDefaultTheme() {
        document.body.classList.add('light-mode');
    }

    function hideLightThemeButton() {
        document.querySelector('.btn-light').style.display = 'none';
    }

    function toggleThemeButtons() {
        document.querySelector('.btn-light').style.display =
            document.body.classList.contains('light-mode') ? 'none' : 'block';
        document.querySelector('.btn-dark').style.transform =
            document.body.classList.contains('light-mode') ? 'rotateY(0deg)' : 'rotateY(180deg)';
    }
});

javascript html css
1个回答
0
投票

将此标签放在

<head>
中(在任何其他标签之前)。
由于此脚本放置的渲染阻塞性质,这将防止样式闪烁(或初始主题切换动画):

<script>
// IMPORTANT: set this in <HEAD> top before any other tag.
const setTheme = (theme) => {
  theme ??= localStorage.theme || "light";
  document.documentElement.dataset.theme = theme;
  localStorage.theme = theme;
};
setTheme();
</script>

然后,在 DOM 就绪脚本中使用:

// This script goes right before the closing </body> tag
// or in a DOMContentLoaded function or inside a script with defer attribute
// Add event listener to the theme buttons
document.querySelectorAll("[data-set-theme]").forEach(elBtn => {
  elBtn.addEventListener("click", () => {
    setTheme(elBtn.dataset.setTheme);
  });
});

注意主题按钮上的

data-set-theme
属性:

<button type="button" data-set-theme="light">Light Theme</button>
<button type="button" data-set-theme="dark">Dark Theme</button>
    

在 CSS 中定义你的调色板,如:

/* Palete de cores */
:root {
  --primary-color: #1B1B1B;
  --bg-primary-color: #0080FF;
  /* Add more theme colors here */
}

[data-theme="dark"] {
  --primary-color: #EDEDED;
  --bg-primary-color: #00437B;
  /* Add more theme colors here */
}

并使用调色板,例如:

body {
  color: var(--primary-color);
  background-color: var(--bg-primary-color);
}

并应用每个主题的样式,例如:

#someElement {
  /* "light" (default) theme styles go here */
}

[data-theme="dark"] {
  #someElement {
    /* "dark" theme overrides go here */
  }
}

在 jsBin.com 上进行演示

© www.soinside.com 2019 - 2024. All rights reserved.