Переключение между светлым и темным режимами

Я написал сценарий с использованием JavaScript, который позволяет мне определять предпочтительный цветовой режим пользователя и переключаться между светлым и темным режимами с помощью кнопки. Но все это нужно настраивать для каждой страницы.

Есть ли более простое решение для определения предпочтительного цветового режима и переключения между двумя режимами с помощью переключателя (кнопки)? Поскольку в CSS уже есть функция prefers-color-scheme, мне нужно только знать, как переключаться между светлым и темным режимами с помощью кнопки в качестве пользователя.

Вот мой текущий код, написанный на простом JS:

window.onload = detectTheme()
function detectTheme() {
// This detects the device color mode when the user enters the webpage

    var theme = document.getElementById("theme");
    // Get the ID from the link we want to change

    if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
        theme.href = '/link/to/darkmode/file'
        // Changing the file based on the color mode ("dark" file for dark-mode)
    
    }
    else if (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches) {
        theme.href = '/link/to/lightmode/file'
        // Changing the file based on the color mode ("light" file for light-mode)
            
    }
}


var switchLD = document.getElementById("switch");
// This is the ID from the switch button

switchLD.onclick = function toggleTheme() { 

    var theme = document.getElementById("theme");

    // Checks what color-mode file is used
    if (theme.getAttribute('href') == '/link/to/lightmode/file') { 
        theme.href = '/link/to/darkmode/file'
        // Changing the file from light to darkmode
    }
    else if (theme.getAttribute('href') == '/link/to/darkmode/file') {
        theme.href = '/link/to/lightmode/file'
        // Changing the file from dark to lightmode
    }
}  


Any answer would help me a lot. If there is a solution using only CSS (or SCSS / SASS), I'd love to use it.

person JueK3y    schedule 28.02.2021    source источник
comment
Вы видели это? youtube.com/watch?v=rXuHGLzSmSE   -  person ThatPurpleGuy    schedule 28.02.2021
comment
Отвечает ли это на ваш вопрос? Как переключить темную тему для всей страницы?   -  person Mohd Abdul Mujib    schedule 28.02.2021


Ответы (2)


Комментарий ThatPurpleGuy фактически ответил на мой вопрос.

В принципе, предпочтительная цветовая схема не используется. JS только определяет, использует ли пользователь темный или светлый режим, а затем корректирует класс в теге body. В зависимости от того, какой класс находится в теге (светлый или темный), применяются разные переменные CSS.

Вот ссылка на руководство YT: https://www.youtube.com/watch?v=rXuHGLzSmSE

person JueK3y    schedule 24.03.2021

Я загружаю весь код переключения между светлой и темной темами с помощью HTML / CSS / JavaScript

HTML

const sunMoonContainer = document.querySelector('.sun-moon-container')
document.querySelector('.theme-toggle-button').addEventListener('click',() =>{
    
    document.body.classList.toggle('dark')

    const currentRotation = parseInt(getComputedStyle(sunMoonContainer).getPropertyValue('--rotation'))

    sunMoonContainer.style.setProperty('--rotation',currentRotation+360)


})
body {
  --accet-color: orangered;
  --text-color: black;
  --background-color: white;
  --button-text-color: var(var(--background-color));
  --transition-delay: 1s;

  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;

  background-color: var(--background-color);
  color: var(--text-color);
  overflow: hidden;
  transition: var(--transition-delay);
}

body.dark {
  --accet-color: #d0d066;
  --text-color: white;
  --background-color: #333;
  --button-text-color: #333;
}

.title {
  margin: 0;
  margin-bottom: 0.5rem;
}

.theme-toggle-button {
  background-color: var(--accet-color);
  color: var(--background-color);
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  padding: 0.5em 1em;
  border-radius: 0.3em;
  border: none;
  outline: none;
  transition: var(--transition-delay);
}

.theme-toggle-button:hover,
.theme-toggle-button:focus {
  transform: scale(1.1);
}

.sun-moon-container {
  --rotation: 0;
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  pointer-events: none;
  top: 0;
  height: 200vmin;
  transform: rotate(calc(var(--rotation) * 1deg));
  transition: transform var(--transition-delay);
}

.fas.fa-sun {
  top: 5%;
  opacity: 1;
}

.fas.fa-moon {
  /* bottom: 5%; */
  top: 5%;
  opacity: 0;
}

.dark .fas.fa-sun {
  opacity: 0;
}

.dark .fas.fa-moon {
  opacity: 1;
}

.fas.fa-sun,
.fas.fa-moon {
  position: absolute;
  /*  transition: opacity var(--transition-delay); */
  fill: var(--accet-color);
}

.dark .sun-moon-container {
  --rotation: 360;
}
<!DOCTYPE html>
<html lang="en">
   <link rel="stylesheet" href="/style.css">
   <script src="/script.js" defer></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" />
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body class="">
    <div class="sun-moon-container">
        <h2 class="sun"><i class="fas fa-sun"></i></h2>
        <h2 class="moon"> <i class="fas fa-moon"></i></h2>
    </div>
    
   
    <h2 class="title">Theme Swaper</h2>
    <button class="theme-toggle-button">Theme Swaper</button>

    
</body>
</html>

person Hash    schedule 13.04.2021
comment
Привет, Хэш - подумайте также о том, чтобы вкратце объяснить, в чем было решение. - person Sterex; 13.04.2021
comment
@Sterex Это решение вышеуказанного вопроса, переключение между светлым и темным режимами, и я поделился простым кодом, который я использовал на своем веб-сайте для переключения между светлым и темным режимами. Надеюсь, теперь тебе все ясно - person Hash; 13.04.2021