Показать сообщение отдельно
  #7 (permalink)  
Старый 10.05.2022, 18:06
Профессор
Отправить личное сообщение для Nexus Посмотреть профиль Найти все сообщения от Nexus
 
Регистрация: 04.12.2012
Сообщений: 3,733

Можно так сделать:

/index.html
<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="/src/dark.css" id="theme-css-file" />
    <script src="/src/index.js"></script>
  </head>

  <body>
    <div>Switch theme:</div>
    <button type="button" data-set-theme-file="/src/light.css">Light</button>
    <button type="button" data-set-theme-file="/src/dark.css">Dark</button>
  </body>
</html>


/src/dark.css
body {
  background: #333;
  color: #fff;
}


/src/light.css
body {
  background: #eee;
  color: #333;
}


/src/index.js
window.addEventListener("click", function (e) {
  const selector = "[data-set-theme-file]";
  let target = e.target;
  if (
    !target ||
    !target.matches ||
    (!target.matches(selector) && !(target = target.closest(selector)))
  ) {
    return;
  }

  const newCssFilePath = target.getAttribute("data-set-theme-file");
  const styleElement = document.querySelector("#theme-css-file");
  if (!newCssFilePath || !styleElement) {
    return;
  }

  styleElement.href = newCssFilePath;
});
Ответить с цитированием